diff --git a/CMake/FindTBB.cmake b/CMake/FindTBB.cmake index a0cafc3f9..4bb4accdd 100644 --- a/CMake/FindTBB.cmake +++ b/CMake/FindTBB.cmake @@ -174,7 +174,7 @@ endif () # will never adequately match the user's setup, so there is no feasible way # to detect the "best" version to use. The user will have to manually # select the right files. (Chances are the distributions are shipping their -# custom version of tbb, anyway, so the problem is probably nonexistant.) +# custom version of tbb, anyway, so the problem is probably nonexistent.) if (WIN32 AND MSVC) set(COMPILER_PREFIX "vc7.1") if (MSVC_VERSION EQUAL 1400) diff --git a/CMake/VTKmCheckPyexpander.cmake b/CMake/VTKmCheckPyexpander.cmake index 318eb99b4..c1d00332b 100644 --- a/CMake/VTKmCheckPyexpander.cmake +++ b/CMake/VTKmCheckPyexpander.cmake @@ -70,7 +70,7 @@ if(${diff_result}) # If diff returned non-zero, it failed and the two files are different. get_filename_component(filename ${SOURCE_FILE} NAME) message(SEND_ERROR - "The source file ${filename} does not match the generated file. If you have modified this file directly, then you have messed up. Modify the ${filename}.in file instead and then copy the pyexpander result to ${filename}. If you modified ${filename}.in, then you might just need to copy the pyresult back to the source directory. If you have not modifed either, then you have likely checked out an inappropriate change. Check the git logs to see what changes were made. + "The source file ${filename} does not match the generated file. If you have modified this file directly, then you have messed up. Modify the ${filename}.in file instead and then copy the pyexpander result to ${filename}. If you modified ${filename}.in, then you might just need to copy the pyresult back to the source directory. If you have not modified either, then you have likely checked out an inappropriate change. Check the git logs to see what changes were made. If the changes have resulted from modifying ${filename}.in, then you can finish by moving ${GENERATED_FILE}.save over ${SOURCE_FILE}") else() # Now that we have done the comparison, remove the generated file so there is diff --git a/CMake/VTKmCheckSourceInBuild.cmake b/CMake/VTKmCheckSourceInBuild.cmake index f0f7af500..fa5704f02 100644 --- a/CMake/VTKmCheckSourceInBuild.cmake +++ b/CMake/VTKmCheckSourceInBuild.cmake @@ -37,6 +37,7 @@ set(FILES_TO_CHECK ) set(EXCEPTIONS + kxsort.h ) set(DIRECTORY_EXCEPTIONS diff --git a/CMake/VTKmConfig.cmake.in b/CMake/VTKmConfig.cmake.in old mode 100755 new mode 100644 index fc2a90096..7a8e42e4b --- a/CMake/VTKmConfig.cmake.in +++ b/CMake/VTKmConfig.cmake.in @@ -53,7 +53,7 @@ set(VTKm_ENABLE_EGL_CONTEXT "@VTKm_ENABLE_EGL_CONTEXT@") set(VTKm_ENABLE_MPI "@VTKm_ENABLE_MPI@") # This is true when the package is still in the build directory (not installed) -if(CMAKE_CURRENT_LIST_DIR STREQUAL "@VTKm_BINARY_DIR@/@VTKm_INSTALL_CONFIG_DIR@") +if(CMAKE_CURRENT_LIST_DIR STREQUAL "@VTKm_BUILD_CMAKE_BASE_DIR@/@VTKm_INSTALL_CONFIG_DIR@") set(VTKm_PACKAGE_IN_BUILD TRUE) endif() diff --git a/CMake/doxyfile.in b/CMake/doxyfile.in index ba597c691..acfae5ce0 100644 --- a/CMake/doxyfile.in +++ b/CMake/doxyfile.in @@ -157,6 +157,8 @@ EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = */testing/* EXCLUDE_PATTERNS += */examples/* EXCLUDE_PATTERNS += UnitTest* +EXCLUDE_PATTERNS += */vtkmdiy/fmt/* +EXCLUDE_PATTERNS += */vtkmdiy/thread/* EXCLUDE_SYMBOLS = thrust EXCLUDE_SYMBOLS += detail diff --git a/CMakeLists.txt b/CMakeLists.txt index bb6715486..8daa80334 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -55,9 +55,15 @@ endif() if (NOT DEFINED VTKm_INSTALL_BIN_DIR) set(VTKm_INSTALL_BIN_DIR "bin") endif() -if (NOT DEFINED VTKm_INSTALL_CMAKE_MODULE_DIR) - set(VTKm_INSTALL_CMAKE_MODULE_DIR "share/vtkm-${VTKm_VERSION_MAJOR}.${VTKm_VERSION_MINOR}/cmake") +if (NOT DEFINED VTKm_INSTALL_SHARE_DIR) + set(VTKm_INSTALL_SHARE_DIR "share/vtkm-${VTKm_VERSION_MAJOR}.${VTKm_VERSION_MINOR}") endif() +if (NOT DEFINED VTKm_INSTALL_CMAKE_MODULE_DIR) + set(VTKm_INSTALL_CMAKE_MODULE_DIR "${VTKm_INSTALL_SHARE_DIR}/cmake") +endif() +if (NOT DEFINED VTKm_BUILD_CMAKE_BASE_DIR) + set(VTKm_BUILD_CMAKE_BASE_DIR "${VTKm_BINARY_DIR}") +endif () set(VTKm_BINARY_INCLUDE_DIR "${VTKm_BINARY_DIR}/include") @@ -65,9 +71,6 @@ if (NOT DEFINED VTKm_EXPORT_NAME) set(VTKm_EXPORT_NAME "VTKmTargets") endif() - -set(VTKm_EXPORT_NAME "VTKmTargets") - #----------------------------------------------------------------------------- # vtkm_option(variable doc [initial]) # Provides an option if it is not already defined. @@ -108,14 +111,19 @@ vtkm_option(VTKm_INSTALL_ONLY_LIBRARIES "install only vtk-m libraries and no hea # VTK does. vtkm_option(VTKm_USE_DEFAULT_SYMBOL_VISIBILITY "Don't explicitly hide symbols from libraries." OFF) +vtkm_option(BUILD_SHARED_LIBS "Build VTK-m with shared libraries" ON) +set(VTKm_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) + mark_as_advanced( VTKm_NO_ASSERT VTKm_INSTALL_ONLY_LIBRARIES VTKm_USE_DEFAULT_SYMBOL_VISIBILITY ) -vtkm_option(BUILD_SHARED_LIBS "Build VTK-m with shared libraries" ON) -set(VTKm_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) +#----------------------------------------------------------------------------- +# When using C++11 support make sure you use the standard C++ extensions rather +# than compiler-specific versions of the extensions (to preserve portability). +set(CMAKE_CXX_EXTENSIONS False) # Setup default build types include(VTKmBuildType) @@ -215,7 +223,7 @@ include(CMakePackageConfigHelpers) configure_package_config_file( ${VTKm_SOURCE_DIR}/CMake/VTKmConfig.cmake.in - ${VTKm_BINARY_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfig.cmake + ${VTKm_BUILD_CMAKE_BASE_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfig.cmake INSTALL_DESTINATION ${VTKm_INSTALL_CONFIG_DIR} PATH_VARS VTKm_INSTALL_INCLUDE_DIR @@ -226,25 +234,25 @@ configure_package_config_file( ) write_basic_package_version_file( - ${VTKm_BINARY_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfigVersion.cmake + ${VTKm_BUILD_CMAKE_BASE_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfigVersion.cmake VERSION ${VTKm_VERSION} COMPATIBILITY ExactVersion ) if(NOT VTKm_INSTALL_ONLY_LIBRARIES) install( FILES - ${VTKm_BINARY_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfig.cmake - ${VTKm_BINARY_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfigVersion.cmake + ${VTKm_BUILD_CMAKE_BASE_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfig.cmake + ${VTKm_BUILD_CMAKE_BASE_DIR}/${VTKm_INSTALL_CONFIG_DIR}/VTKmConfigVersion.cmake DESTINATION ${VTKm_INSTALL_CONFIG_DIR} ) # Install the readme and license files. install(FILES ${VTKm_SOURCE_DIR}/README.md - DESTINATION ${VTKm_INSTALL_CONFIG_DIR} + DESTINATION ${VTKm_INSTALL_SHARE_DIR} RENAME VTKmREADME.md ) install(FILES ${VTKm_SOURCE_DIR}/LICENSE.txt - DESTINATION ${VTKm_INSTALL_CONFIG_DIR} + DESTINATION ${VTKm_INSTALL_SHARE_DIR} RENAME VTKmLICENSE.txt ) @@ -277,17 +285,20 @@ if(NOT VTKm_INSTALL_ONLY_LIBRARIES) ) endif() -# Enable CPack packaging -set(CPACK_PACKAGE_DESCRIPTION_FILE ${VTKm_SOURCE_DIR}/README.md) -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "The VTKm Toolkit") -set(CPACK_PACKAGE_NAME "VTKm") -set(CPACK_PACKAGE_VERSION_MAJOR ${VTKm_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${VTKm_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${VTKm_VERSION_PATCH}) -set(CPACK_PACKAGE_FILE_NAME "VTKm-${VTKm_VERSION}") -set(CPACK_RESOURCE_FILE_LICENSE ${VTKm_SOURCE_DIR}/LICENSE.txt) -set(CPACK_RESOURCE_FILE_README ${VTKm_SOURCE_DIR}/README.md) -include(CPack) +vtkm_option(VTKm_ENABLE_CPACK "Enable CPack packaging of VTKm" ON) +if (VTKm_ENABLE_CPACK) + # Enable CPack packaging + set(CPACK_PACKAGE_DESCRIPTION_FILE ${VTKm_SOURCE_DIR}/README.md) + set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "The VTKm Toolkit") + set(CPACK_PACKAGE_NAME "VTKm") + set(CPACK_PACKAGE_VERSION_MAJOR ${VTKm_VERSION_MAJOR}) + set(CPACK_PACKAGE_VERSION_MINOR ${VTKm_VERSION_MINOR}) + set(CPACK_PACKAGE_VERSION_PATCH ${VTKm_VERSION_PATCH}) + set(CPACK_PACKAGE_FILE_NAME "VTKm-${VTKm_VERSION}") + set(CPACK_RESOURCE_FILE_LICENSE ${VTKm_SOURCE_DIR}/LICENSE.txt) + set(CPACK_RESOURCE_FILE_README ${VTKm_SOURCE_DIR}/README.md) + include(CPack) +endif () #----------------------------------------------------------------------------- #add the benchmarking folder diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ff08da21..744a98fad 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -436,7 +436,7 @@ authorized developers may add a comment with a single *trailing* line: Do: merge to ask that the change be merged into the upstream repository. By -convention, only merge if you have recieved `+1` . Do not request a merge +convention, only merge if you have received `+1` . Do not request a merge if any `-1` review comments have not been resolved. ### Merge Success ### diff --git a/CTestCustom.cmake.in b/CTestCustom.cmake.in index 23286b660..4055316a9 100644 --- a/CTestCustom.cmake.in +++ b/CTestCustom.cmake.in @@ -20,7 +20,7 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION ".*warning: ignoring loop annotation.*" - ".*diy.include.diy.*WShadow.*" # exclude `diy` shadow warnings. - ".*diy.include.diy.*note: shadowed.*" # exclude `diy` shadow warnings. - ".*diy.include.diy.storage.hpp.*Wunused-result.*" # this is a TODO in DIY. + ".*warning: Included by graph for.*not generated, too many nodes. Consider increasing DOT_GRAPH_MAX_NODES." + ".*diy.include.*diy.mpi.io.hpp.*Wconversion.*" + ".*diy.include.*diy.mpi.datatypes.hpp.*Wunused-parameter.*" ) diff --git a/LICENSE.txt b/LICENSE.txt index c5c31b91c..fc320ef1c 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -74,6 +74,8 @@ CMake/FindTBB.cmake CMake/FindGLEW.cmake Utilities vtkm/cont/tbb/internal/parallel_sort.h +vtkm/cont/tbb/internal/parallel_radix_sort_tbb.h +vtkm/cont/tbb/internal/kxsort.h vtkm/testing/OptionParser.h vtkm/internal/brigand.hpp version.txt diff --git a/benchmarking/BenchmarkDeviceAdapter.cxx b/benchmarking/BenchmarkDeviceAdapter.cxx index 0b81786ba..094989175 100644 --- a/benchmarking/BenchmarkDeviceAdapter.cxx +++ b/benchmarking/BenchmarkDeviceAdapter.cxx @@ -169,13 +169,13 @@ const static std::string DIVIDER(40, '-'); template class BenchmarkDeviceAdapter { - typedef vtkm::cont::StorageTagBasic StorageTag; + using StorageTag = vtkm::cont::StorageTagBasic; - typedef vtkm::cont::ArrayHandle IdArrayHandle; + using IdArrayHandle = vtkm::cont::ArrayHandle; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; - typedef vtkm::cont::Timer Timer; + using Timer = vtkm::cont::Timer; public: // Various kernels used by the different benchmarks to accelerate @@ -183,8 +183,8 @@ public: template struct FillTestValueKernel : vtkm::exec::FunctorBase { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; - typedef typename ValueArrayHandle::template ExecutionTypes::Portal PortalType; + using ValueArrayHandle = vtkm::cont::ArrayHandle; + using PortalType = typename ValueArrayHandle::template ExecutionTypes::Portal; PortalType Output; @@ -200,8 +200,8 @@ public: template struct FillScaledTestValueKernel : vtkm::exec::FunctorBase { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; - typedef typename ValueArrayHandle::template ExecutionTypes::Portal PortalType; + using ValueArrayHandle = vtkm::cont::ArrayHandle; + using PortalType = typename ValueArrayHandle::template ExecutionTypes::Portal; PortalType Output; const vtkm::Id IdScale; @@ -219,8 +219,8 @@ public: template struct FillModuloTestValueKernel : vtkm::exec::FunctorBase { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; - typedef typename ValueArrayHandle::template ExecutionTypes::Portal PortalType; + using ValueArrayHandle = vtkm::cont::ArrayHandle; + using PortalType = typename ValueArrayHandle::template ExecutionTypes::Portal; PortalType Output; const vtkm::Id Modulus; @@ -238,8 +238,8 @@ public: template struct FillBinaryTestValueKernel : vtkm::exec::FunctorBase { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; - typedef typename ValueArrayHandle::template ExecutionTypes::Portal PortalType; + using ValueArrayHandle = vtkm::cont::ArrayHandle; + using PortalType = typename ValueArrayHandle::template ExecutionTypes::Portal; PortalType Output; const vtkm::Id Modulus; @@ -261,7 +261,7 @@ private: template struct BenchCopy { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; ValueArrayHandle ValueHandle_src; ValueArrayHandle ValueHandle_dst; @@ -302,7 +302,7 @@ private: template struct BenchCopyIf { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; const vtkm::Id PERCENT_VALID; const vtkm::Id N_VALID; @@ -359,7 +359,7 @@ private: template struct BenchLowerBounds { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; const vtkm::Id N_VALS; const vtkm::Id PERCENT_VALUES; @@ -415,10 +415,10 @@ private: template struct BenchReduce { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; ValueArrayHandle InputHandle; - // We don't actually use this, but we need it to prevent sufficently + // We don't actually use this, but we need it to prevent sufficiently // smart compilers from optimizing the Reduce call out. Value Result; @@ -461,7 +461,7 @@ private: template struct BenchReduceByKey { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; const vtkm::Id N_KEYS; const vtkm::Id PERCENT_KEYS; @@ -518,7 +518,7 @@ private: template struct BenchScanInclusive { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; ValueArrayHandle ValueHandle, OutHandle; VTKM_CONT @@ -553,7 +553,7 @@ private: template struct BenchScanExclusive { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; ValueArrayHandle ValueHandle, OutHandle; @@ -589,7 +589,7 @@ private: template struct BenchSort { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; ValueArrayHandle ValueHandle; std::mt19937 Rng; @@ -631,7 +631,7 @@ private: template struct BenchSortByKey { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; std::mt19937 Rng; vtkm::Id N_KEYS; @@ -797,7 +797,7 @@ private: template struct BenchUnique { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; const vtkm::Id N_VALID; const vtkm::Id PERCENT_VALID; @@ -853,7 +853,7 @@ private: template struct BenchUpperBounds { - typedef vtkm::cont::ArrayHandle ValueArrayHandle; + using ValueArrayHandle = vtkm::cont::ArrayHandle; const vtkm::Id N_VALS; const vtkm::Id PERCENT_VALS; diff --git a/benchmarking/BenchmarkFieldAlgorithms.cxx b/benchmarking/BenchmarkFieldAlgorithms.cxx index 9483a003b..d4d51fd4d 100644 --- a/benchmarking/BenchmarkFieldAlgorithms.cxx +++ b/benchmarking/BenchmarkFieldAlgorithms.cxx @@ -205,7 +205,7 @@ class GenerateEdges : public vtkm::worklet::WorkletMapPointToCell public: typedef void ControlSignature(CellSetIn cellset, WholeArrayOut<> edgeIds); typedef void ExecutionSignature(PointIndices, ThreadIndices, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const ConnectivityInVec& connectivity, @@ -234,7 +234,7 @@ public: WholeArrayIn<> inputField, FieldOut<> output); typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::Id2& low_high, @@ -321,11 +321,11 @@ using StorageListTag = ::vtkm::cont::StorageListTagBasic; template class BenchmarkFieldAlgorithms { - typedef vtkm::cont::StorageTagBasic StorageTag; + using StorageTag = vtkm::cont::StorageTagBasic; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; - typedef vtkm::cont::Timer Timer; + using Timer = vtkm::cont::Timer; using ValueDynamicHandle = vtkm::cont::DynamicArrayHandleBase; using InterpDynamicHandle = vtkm::cont::DynamicArrayHandleBase; diff --git a/benchmarking/BenchmarkTopologyAlgorithms.cxx b/benchmarking/BenchmarkTopologyAlgorithms.cxx index cd9b81325..812709614 100644 --- a/benchmarking/BenchmarkTopologyAlgorithms.cxx +++ b/benchmarking/BenchmarkTopologyAlgorithms.cxx @@ -59,7 +59,7 @@ public: CellSetIn cellset, FieldOutCell<> outCells); typedef void ExecutionSignature(_1, PointCount, _3); - typedef _2 InputDomain; + using InputDomain = _2; template VTKM_EXEC void operator()(const PointValueVecType& pointValues, @@ -81,7 +81,7 @@ class AverageCellToPoint : public vtkm::worklet::WorkletMapCellToPoint public: typedef void ControlSignature(FieldInCell<> inCells, CellSetIn topology, FieldOut<> outPoints); typedef void ExecutionSignature(_1, _3, CellCount); - typedef _2 InputDomain; + using InputDomain = _2; template VTKM_EXEC void operator()(const CellVecType& cellValues, @@ -110,7 +110,7 @@ public: CellSetIn cellset, FieldOutCell outCaseId); typedef void ExecutionSignature(_1, _3); - typedef _2 InputDomain; + using InputDomain = _2; T IsoValue; @@ -123,7 +123,7 @@ public: template VTKM_EXEC void operator()(const FieldInType& fieldIn, vtkm::IdComponent& caseNumber) const { - typedef typename vtkm::VecTraits::ComponentType FieldType; + using FieldType = typename vtkm::VecTraits::ComponentType; const FieldType iso = static_cast(this->IsoValue); caseNumber = ((fieldIn[0] > iso) | (fieldIn[1] > iso) << 1 | (fieldIn[2] > iso) << 2 | @@ -143,11 +143,11 @@ using StorageListTag = ::vtkm::cont::StorageListTagBasic; template class BenchmarkTopologyAlgorithms { - typedef vtkm::cont::StorageTagBasic StorageTag; + using StorageTag = vtkm::cont::StorageTagBasic; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; - typedef vtkm::cont::Timer Timer; + using Timer = vtkm::cont::Timer; using ValueDynamicHandle = vtkm::cont::DynamicArrayHandleBase; diff --git a/examples/isosurface/IsosurfaceUniformGrid.cxx b/examples/isosurface/IsosurfaceUniformGrid.cxx index 0c0842c59..d83ff1948 100644 --- a/examples/isosurface/IsosurfaceUniformGrid.cxx +++ b/examples/isosurface/IsosurfaceUniformGrid.cxx @@ -245,7 +245,7 @@ int main(int argc, char* argv[]) vtkm::filter::MarchingCubes filter; filter.SetGenerateNormals(true); filter.SetMergeDuplicatePoints(false); - filter.SetIsoValue(0, 0.5); + filter.SetIsoValue(0, 0.1); vtkm::filter::Result result = filter.Execute(dataSet, dataSet.GetField("nodevar")); filter.MapFieldOntoOutput(result, dataSet.GetField("nodevar")); diff --git a/examples/tau_timing/TauTiming.cxx b/examples/tau_timing/TauTiming.cxx index af72d9722..50f99d8c8 100644 --- a/examples/tau_timing/TauTiming.cxx +++ b/examples/tau_timing/TauTiming.cxx @@ -64,14 +64,14 @@ VTKM_EXEC_CONT vtkm::Vec Normalize(vtkm::Vec v) return one / magnitude * v; } -typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; +using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; class TangleField : public vtkm::worklet::WorkletMapField { public: typedef void ControlSignature(FieldIn vertexId, FieldOut v); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; const vtkm::Id xdim, ydim, zdim; const vtkm::FloatDefault xmin, ymin, zmin, xmax, ymax, zmax; @@ -343,9 +343,9 @@ void RenderRTTest(const vtkm::cont::DataSet& ds, int N) if (printProgress && i % 10 == 0) std::cout << " " << i << " of " << N << std::endl; - typedef vtkm::rendering::MapperRayTracer M; - typedef vtkm::rendering::CanvasRayTracer C; - typedef vtkm::rendering::View3D V3; + using M = vtkm::rendering::MapperRayTracer; + using C = vtkm::rendering::CanvasRayTracer; + using V3 = vtkm::rendering::View3D; //std::cout<<"Render: "< TopologicalDimensionsTag; + using TopologicalDimensionsTag = vtkm::CellTopologicalDimensionsTag; /// \brief A tag specifying whether the number of points is fixed. /// @@ -74,7 +74,7 @@ struct CellTraits /// \c CellTraitsTagSizeVariable, then the number of points is not known at /// compile time. /// - typedef vtkm::CellTraitsTagSizeFixed IsSizeFixed; + using IsSizeFixed = vtkm::CellTraitsTagSizeFixed; /// \brief Number of points in the cell. /// @@ -95,19 +95,19 @@ struct CellTraits template <> \ struct CellTraits \ { \ - const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ - typedef vtkm::CellTopologicalDimensionsTag TopologicalDimensionsTag; \ - typedef vtkm::CellTraitsTagSizeFixed IsSizeFixed; \ - static const vtkm::IdComponent NUM_POINTS = numPoints; \ + static constexpr vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ + using TopologicalDimensionsTag = vtkm::CellTopologicalDimensionsTag; \ + using IsSizeFixed = vtkm::CellTraitsTagSizeFixed; \ + static constexpr vtkm::IdComponent NUM_POINTS = numPoints; \ } #define VTKM_DEFINE_CELL_TRAITS_VARIABLE(name, dimensions) \ template <> \ struct CellTraits \ { \ - const static vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ - typedef vtkm::CellTopologicalDimensionsTag TopologicalDimensionsTag; \ - typedef vtkm::CellTraitsTagSizeVariable IsSizeFixed; \ + static constexpr vtkm::IdComponent TOPOLOGICAL_DIMENSIONS = dimensions; \ + using TopologicalDimensionsTag = vtkm::CellTopologicalDimensionsTag; \ + using IsSizeFixed = vtkm::CellTraitsTagSizeVariable; \ } VTKM_DEFINE_CELL_TRAITS(Empty, 0, 0); diff --git a/vtkm/Matrix.h b/vtkm/Matrix.h index 03404ce9b..897b43d15 100644 --- a/vtkm/Matrix.h +++ b/vtkm/Matrix.h @@ -329,7 +329,7 @@ VTKM_EXEC_CONT void MatrixLUPFactorFindUpperTriangleElements(vtkm::Matrix NewtonsMethod( ScalarType convergeDifference = ScalarType(1e-3), vtkm::IdComponent maxIterations = 10) { - typedef vtkm::Vec VectorType; - typedef vtkm::Matrix MatrixType; + using VectorType = vtkm::Vec; + using MatrixType = vtkm::Matrix; VectorType x = initialGuess; diff --git a/vtkm/Range.h b/vtkm/Range.h index e3428f4d1..847ef143e 100644 --- a/vtkm/Range.h +++ b/vtkm/Range.h @@ -137,13 +137,16 @@ struct Range /// \b Expand range to include other range. /// /// This version of \c Include expands this range just enough to include that - /// of another range. Esentially it is the union of the two ranges. + /// of another range. Essentially it is the union of the two ranges. /// VTKM_EXEC_CONT void Include(const vtkm::Range& range) { - this->Include(range.Min); - this->Include(range.Max); + if (range.IsNonEmpty()) + { + this->Include(range.Min); + this->Include(range.Max); + } } /// \b Return the union of this and another range. diff --git a/vtkm/RangeId.h b/vtkm/RangeId.h index 28f9a5b20..e7e4787c5 100644 --- a/vtkm/RangeId.h +++ b/vtkm/RangeId.h @@ -102,7 +102,7 @@ struct RangeId /// \b Expand range to include other range. /// /// This version of \c Include expands this range just enough to include that - /// of another range. Esentially it is the union of the two ranges. + /// of another range. Essentially it is the union of the two ranges. /// VTKM_EXEC_CONT void Include(const vtkm::RangeId& range) diff --git a/vtkm/RangeId3.h b/vtkm/RangeId3.h index 0849ff93a..16266b7f6 100644 --- a/vtkm/RangeId3.h +++ b/vtkm/RangeId3.h @@ -130,7 +130,7 @@ struct RangeId3 /// \b Expand range to include other range. /// /// This version of \c Include expands the range just enough to include - /// the other range. Esentially it is the union of the two ranges. + /// the other range. Essentially it is the union of the two ranges. /// VTKM_EXEC_CONT void Include(const vtkm::RangeId3& range) diff --git a/vtkm/Transform3D.h b/vtkm/Transform3D.h index a92edd11b..0ebdf5df9 100644 --- a/vtkm/Transform3D.h +++ b/vtkm/Transform3D.h @@ -58,7 +58,7 @@ VTKM_EXEC_CONT vtkm::Vec Transform3DPoint(const vtkm::Matrix& mat /// transformed by the given matrix in homogeneous coordinates. /// /// Unlike Transform3DPoint, this method honors the fourth component of the -/// transformed homogeneous coordiante. This makes it applicable for perspective +/// transformed homogeneous coordinate. This makes it applicable for perspective /// transformations, but requires some more computations. /// template diff --git a/vtkm/TypeTraits.h b/vtkm/TypeTraits.h index 5b4f258fa..03d01984d 100644 --- a/vtkm/TypeTraits.h +++ b/vtkm/TypeTraits.h @@ -63,7 +63,7 @@ struct TypeTraitsVectorTag }; /// The TypeTraits class provides helpful compile-time information about the -/// basic types used in VTKm (and a few others for convienience). The majority +/// basic types used in VTKm (and a few others for convenience). The majority /// of TypeTraits contents are typedefs to tags that can be used to easily /// override behavior of called functions. /// @@ -71,7 +71,7 @@ template class TypeTraits { public: - /// \brief A tag to determing whether the type is integer or real. + /// \brief A tag to determine whether the type is integer or real. /// /// This tag is either TypeTraitsRealTag or TypeTraitsIntegerTag. using NumericTag = vtkm::TypeTraitsUnknownTag; diff --git a/vtkm/Types.h b/vtkm/Types.h index 939a4ef38..61b1fcbed 100644 --- a/vtkm/Types.h +++ b/vtkm/Types.h @@ -48,7 +48,7 @@ * \brief Transportation controls for Control Environment Objects. * * vtkm::cont::arg includes the classes that allows the vtkm::worklet::Dispatchers - * to request Control Environment Objects to be transfered to the Execution Environment. + * to request Control Environment Objects to be transferred to the Execution Environment. * * \namespace vtkm::cont::cuda * \brief CUDA implementation for Control Environment. @@ -749,7 +749,7 @@ protected: /// The \c Vec class is most often used to represent vectors in the /// mathematical sense as a quantity with a magnitude and direction. Vectors /// are, of course, used extensively in computational geometry as well as -/// phyiscal simulations. The \c Vec class can be (and is) repurposed for more +/// physical simulations. The \c Vec class can be (and is) repurposed for more /// general usage of holding a fixed-length sequence of objects. /// /// There is no real limit to the size of the sequence (other than the largest diff --git a/vtkm/UnaryPredicates.h b/vtkm/UnaryPredicates.h index f6e08e24c..1eb446860 100644 --- a/vtkm/UnaryPredicates.h +++ b/vtkm/UnaryPredicates.h @@ -63,4 +63,4 @@ struct LogicalNot } // namespace vtkm -#endif //vtk_m_UnaryPredicates_h \ No newline at end of file +#endif //vtk_m_UnaryPredicates_h diff --git a/vtkm/VecAxisAlignedPointCoordinates.h b/vtkm/VecAxisAlignedPointCoordinates.h index a4face0b5..baf304d95 100644 --- a/vtkm/VecAxisAlignedPointCoordinates.h +++ b/vtkm/VecAxisAlignedPointCoordinates.h @@ -75,7 +75,7 @@ template class VecAxisAlignedPointCoordinates { public: - typedef vtkm::Vec ComponentType; + using ComponentType = vtkm::Vec; static const vtkm::IdComponent NUM_COMPONENTS = detail::VecAxisAlignedPointCoordinatesNumComponents::NUM_COMPONENTS; @@ -132,8 +132,8 @@ private: template struct TypeTraits> { - typedef vtkm::TypeTraitsRealTag NumericTag; - typedef TypeTraitsVectorTag DimensionalityTag; + using NumericTag = vtkm::TypeTraitsRealTag; + using DimensionalityTag = TypeTraitsVectorTag; VTKM_EXEC_CONT static vtkm::VecAxisAlignedPointCoordinates ZeroInitialization() @@ -146,11 +146,11 @@ struct TypeTraits> template struct VecTraits> { - typedef vtkm::VecAxisAlignedPointCoordinates VecType; + using VecType = vtkm::VecAxisAlignedPointCoordinates; - typedef vtkm::Vec ComponentType; - typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; - typedef vtkm::VecTraitsTagSizeStatic IsSizeStatic; + using ComponentType = vtkm::Vec; + using HasMultipleComponents = vtkm::VecTraitsTagMultipleComponents; + using IsSizeStatic = vtkm::VecTraitsTagSizeStatic; static const vtkm::IdComponent NUM_COMPONENTS = VecType::NUM_COMPONENTS; diff --git a/vtkm/VecFromPortal.h b/vtkm/VecFromPortal.h index 940b90bd3..877ecffff 100644 --- a/vtkm/VecFromPortal.h +++ b/vtkm/VecFromPortal.h @@ -89,11 +89,11 @@ template struct TypeTraits> { private: - typedef typename PortalType::ValueType ComponentType; + using ComponentType = typename PortalType::ValueType; public: - typedef typename vtkm::TypeTraits::NumericTag NumericTag; - typedef TypeTraitsVectorTag DimensionalityTag; + using NumericTag = typename vtkm::TypeTraits::NumericTag; + using DimensionalityTag = TypeTraitsVectorTag; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC_CONT @@ -106,11 +106,11 @@ public: template struct VecTraits> { - typedef vtkm::VecFromPortal VecType; + using VecType = vtkm::VecFromPortal; - typedef typename VecType::ComponentType ComponentType; - typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; - typedef vtkm::VecTraitsTagSizeVariable IsSizeStatic; + using ComponentType = typename VecType::ComponentType; + using HasMultipleComponents = vtkm::VecTraitsTagMultipleComponents; + using IsSizeStatic = vtkm::VecTraitsTagSizeVariable; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC_CONT diff --git a/vtkm/VecFromPortalPermute.h b/vtkm/VecFromPortalPermute.h index 2b4c0ef21..286c45029 100644 --- a/vtkm/VecFromPortalPermute.h +++ b/vtkm/VecFromPortalPermute.h @@ -83,12 +83,12 @@ template struct TypeTraits> { private: - typedef vtkm::VecFromPortalPermute VecType; - typedef typename PortalType::ValueType ComponentType; + using VecType = vtkm::VecFromPortalPermute; + using ComponentType = typename PortalType::ValueType; public: - typedef typename vtkm::TypeTraits::NumericTag NumericTag; - typedef TypeTraitsVectorTag DimensionalityTag; + using NumericTag = typename vtkm::TypeTraits::NumericTag; + using DimensionalityTag = TypeTraitsVectorTag; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC_CONT @@ -98,11 +98,11 @@ public: template struct VecTraits> { - typedef vtkm::VecFromPortalPermute VecType; + using VecType = vtkm::VecFromPortalPermute; - typedef typename VecType::ComponentType ComponentType; - typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; - typedef vtkm::VecTraitsTagSizeVariable IsSizeStatic; + using ComponentType = typename VecType::ComponentType; + using HasMultipleComponents = vtkm::VecTraitsTagMultipleComponents; + using IsSizeStatic = vtkm::VecTraitsTagSizeVariable; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC_CONT @@ -126,6 +126,14 @@ struct VecTraits> } }; +template +inline VTKM_EXEC VecFromPortalPermute make_VecFromPortalPermute( + const IndexVecType* index, + const PortalType& portal) +{ + return VecFromPortalPermute(index, portal); +} + } // namespace vtkm #endif //vtk_m_VecFromPortalPermute_h diff --git a/vtkm/VecTraits.h b/vtkm/VecTraits.h index 24059de33..918e64e69 100644 --- a/vtkm/VecTraits.h +++ b/vtkm/VecTraits.h @@ -367,7 +367,7 @@ struct VecTraitsBasic /// \brief VecTraits for Pair types /// -/// Although a pair woudl seem better as a size-2 vector, we treat it as a +/// Although a pair would seem better as a size-2 vector, we treat it as a /// scalar. This is because a \c Vec is assumed to have the same type for /// every component, and a pair in general has a different type for each /// component. Thus we treat a pair as a "scalar" unit. diff --git a/vtkm/VecVariable.h b/vtkm/VecVariable.h index 0e2db0b50..479d067de 100644 --- a/vtkm/VecVariable.h +++ b/vtkm/VecVariable.h @@ -40,7 +40,7 @@ template class VecVariable { public: - typedef T ComponentType; + using ComponentType = T; VTKM_EXEC_CONT VecVariable() @@ -48,8 +48,8 @@ public: { } - template - VTKM_EXEC_CONT VecVariable(const vtkm::VecVariable& src) + template + VTKM_EXEC_CONT VecVariable(const SrcVecType& src) : NumComponents(src.GetNumberOfComponents()) { VTKM_ASSERT(this->NumComponents <= MaxSize); @@ -59,17 +59,6 @@ public: } } - template - VTKM_EXEC_CONT VecVariable(const vtkm::Vec& src) - : NumComponents(SrcSize) - { - VTKM_ASSERT(this->NumComponents <= MaxSize); - for (vtkm::IdComponent index = 0; index < this->NumComponents; index++) - { - this->Data[index] = src[index]; - } - } - VTKM_EXEC_CONT vtkm::IdComponent GetNumberOfComponents() const { return this->NumComponents; } @@ -105,8 +94,8 @@ private: template struct TypeTraits> { - typedef typename vtkm::TypeTraits::NumericTag NumericTag; - typedef TypeTraitsVectorTag DimensionalityTag; + using NumericTag = typename vtkm::TypeTraits::NumericTag; + using DimensionalityTag = TypeTraitsVectorTag; VTKM_EXEC_CONT static vtkm::VecVariable ZeroInitialization() @@ -118,11 +107,11 @@ struct TypeTraits> template struct VecTraits> { - typedef vtkm::VecVariable VecType; + using VecType = vtkm::VecVariable; - typedef typename VecType::ComponentType ComponentType; - typedef vtkm::VecTraitsTagMultipleComponents HasMultipleComponents; - typedef vtkm::VecTraitsTagSizeVariable IsSizeStatic; + using ComponentType = typename VecType::ComponentType; + using HasMultipleComponents = vtkm::VecTraitsTagMultipleComponents; + using IsSizeStatic = vtkm::VecTraitsTagSizeVariable; VTKM_EXEC_CONT static vtkm::IdComponent GetNumberOfComponents(const VecType& vector) diff --git a/vtkm/VectorAnalysis.h b/vtkm/VectorAnalysis.h index 43a8921a9..65e3757c8 100644 --- a/vtkm/VectorAnalysis.h +++ b/vtkm/VectorAnalysis.h @@ -22,7 +22,7 @@ #ifndef vtk_m_VectorAnalysis_h #define vtk_m_VectorAnalysis_h -// This header file defines math functions that deal with linear albegra funcitons +// This header file defines math functions that deal with linear albegra functions #include #include diff --git a/vtkm/cont/ArrayHandle.cxx b/vtkm/cont/ArrayHandle.cxx index 1d94c9a60..8520c861d 100644 --- a/vtkm/cont/ArrayHandle.cxx +++ b/vtkm/cont/ArrayHandle.cxx @@ -21,49 +21,10 @@ #define vtkm_cont_ArrayHandle_cxx #include -#ifdef VTKM_MSVC -#define _VTKM_SHARED_PTR_INSTANTIATE(Type) \ - template class VTKM_CONT_EXPORT \ - std::shared_ptr::InternalStruct>; \ - template class VTKM_CONT_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; \ - template class VTKM_CONT_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; \ - template class VTKM_CONT_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; - -_VTKM_SHARED_PTR_INSTANTIATE(char) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int8) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::UInt8) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int16) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::UInt16) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int32) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::UInt32) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Int64) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::UInt64) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Float32) -_VTKM_SHARED_PTR_INSTANTIATE(vtkm::Float64) - -#undef _VTKM_SHARED_PTR_INSTANTIATE -#endif // VTKM_MSVC - namespace vtkm { namespace cont { -namespace internal -{ - -ExecutionArrayInterfaceBasicBase::ExecutionArrayInterfaceBasicBase(StorageBasicBase& storage) - : ControlStorage(storage) -{ -} - -ExecutionArrayInterfaceBasicBase::~ExecutionArrayInterfaceBasicBase() -{ -} - -} // end namespace internal #define _VTKM_ARRAYHANDLE_INSTANTIATE(Type) \ template class VTKM_CONT_EXPORT ArrayHandle; \ diff --git a/vtkm/cont/ArrayHandle.h b/vtkm/cont/ArrayHandle.h index 09d910314..f33ee7bda 100644 --- a/vtkm/cont/ArrayHandle.h +++ b/vtkm/cont/ArrayHandle.h @@ -485,12 +485,13 @@ public: struct VTKM_ALWAYS_EXPORT InternalStruct { - StorageType ControlArray; - bool ControlArrayValid; + mutable StorageType ControlArray; + mutable bool ControlArrayValid; - std::unique_ptr> + mutable std::unique_ptr< + vtkm::cont::internal::ArrayHandleExecutionManagerBase> ExecutionArray; - bool ExecutionArrayValid; + mutable bool ExecutionArrayValid; }; VTKM_CONT @@ -661,32 +662,6 @@ VTKM_NEVER_EXPORT VTKM_CONT inline void printSummary_ArrayHandle( #ifndef vtkm_cont_ArrayHandle_cxx -#ifdef VTKM_MSVC -#define _VTKM_SHARED_PTR_EXPORT(Type) \ - extern template class VTKM_CONT_TEMPLATE_EXPORT \ - std::shared_ptr::InternalStruct>; \ - extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; \ - extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; \ - extern template class VTKM_CONT_TEMPLATE_EXPORT std::shared_ptr< \ - vtkm::cont::ArrayHandle, vtkm::cont::StorageTagBasic>::InternalStruct>; - -_VTKM_SHARED_PTR_EXPORT(char) -_VTKM_SHARED_PTR_EXPORT(vtkm::Int8) -_VTKM_SHARED_PTR_EXPORT(vtkm::UInt8) -_VTKM_SHARED_PTR_EXPORT(vtkm::Int16) -_VTKM_SHARED_PTR_EXPORT(vtkm::UInt16) -_VTKM_SHARED_PTR_EXPORT(vtkm::Int32) -_VTKM_SHARED_PTR_EXPORT(vtkm::UInt32) -_VTKM_SHARED_PTR_EXPORT(vtkm::Int64) -_VTKM_SHARED_PTR_EXPORT(vtkm::UInt64) -_VTKM_SHARED_PTR_EXPORT(vtkm::Float32) -_VTKM_SHARED_PTR_EXPORT(vtkm::Float64) - -#undef _VTKM_SHARED_PTR_EXPORT -#endif // VTKM_MSVC - namespace vtkm { namespace cont diff --git a/vtkm/cont/ArrayHandle.hxx b/vtkm/cont/ArrayHandle.hxx index 092ab589c..ca11c1ebf 100644 --- a/vtkm/cont/ArrayHandle.hxx +++ b/vtkm/cont/ArrayHandle.hxx @@ -299,9 +299,8 @@ void ArrayHandle::PrepareForDevice(DeviceAdapterTag) const this->SyncControlArray(); // Need to change some state that does not change the logical state from // an external point of view. - InternalStruct* internals = const_cast(this->Internals.get()); - internals->ExecutionArray.reset(); - internals->ExecutionArrayValid = false; + this->Internals->ExecutionArray.reset(); + this->Internals->ExecutionArrayValid = false; } } @@ -309,10 +308,9 @@ void ArrayHandle::PrepareForDevice(DeviceAdapterTag) const VTKM_ASSERT(!this->Internals->ExecutionArrayValid); // Need to change some state that does not change the logical state from // an external point of view. - InternalStruct* internals = const_cast(this->Internals.get()); - internals->ExecutionArray.reset( + this->Internals->ExecutionArray.reset( new vtkm::cont::internal::ArrayHandleExecutionManager( - &internals->ControlArray)); + &this->Internals->ControlArray)); } template @@ -322,19 +320,18 @@ void ArrayHandle::SyncControlArray() const { // Need to change some state that does not change the logical state from // an external point of view. - InternalStruct* internals = const_cast(this->Internals.get()); if (this->Internals->ExecutionArrayValid) { - internals->ExecutionArray->RetrieveOutputData(&internals->ControlArray); - internals->ControlArrayValid = true; + this->Internals->ExecutionArray->RetrieveOutputData(&this->Internals->ControlArray); + this->Internals->ControlArrayValid = true; } else { // This array is in the null state (there is nothing allocated), but // the calling function wants to do something with the array. Put this // class into a valid state by allocating an array of size 0. - internals->ControlArray.Allocate(0); - internals->ControlArrayValid = true; + this->Internals->ControlArray.Allocate(0); + this->Internals->ControlArrayValid = true; } } } diff --git a/vtkm/cont/ArrayHandleTransform.h b/vtkm/cont/ArrayHandleTransform.h index 120d8184f..624e8f428 100644 --- a/vtkm/cont/ArrayHandleTransform.h +++ b/vtkm/cont/ArrayHandleTransform.h @@ -436,7 +436,7 @@ public: { throw vtkm::cont::ErrorInternal( "ArrayHandleTransform read only. " - "There should be no occurance of the ArrayHandle trying to pull " + "There should be no occurrence of the ArrayHandle trying to pull " "data from the execution environment."); } diff --git a/vtkm/cont/ArrayHandleVirtualCoordinates.h b/vtkm/cont/ArrayHandleVirtualCoordinates.h index c33ef7980..ef1abeb71 100644 --- a/vtkm/cont/ArrayHandleVirtualCoordinates.h +++ b/vtkm/cont/ArrayHandleVirtualCoordinates.h @@ -441,7 +441,7 @@ public: } template - bool IsSameType() const + bool IsType() const { return this->GetArrayHandleWrapper() != nullptr; } @@ -488,7 +488,7 @@ void CastAndCall(const vtkm::cont::ArrayHandleVirtualCoordinates& coords, Functor&& f, Args&&... args) { - if (coords.IsSameType()) + if (coords.IsType()) { f(coords.Cast(), std::forward(args)...); } diff --git a/vtkm/cont/ArrayPortalToIterators.h b/vtkm/cont/ArrayPortalToIterators.h index 92e9296b2..fa6cf873f 100644 --- a/vtkm/cont/ArrayPortalToIterators.h +++ b/vtkm/cont/ArrayPortalToIterators.h @@ -75,7 +75,7 @@ private: PortalType Portal; }; -/// Convienience function for converting an ArrayPortal to a begin iterator. +/// Convenience function for converting an ArrayPortal to a begin iterator. /// VTKM_SUPPRESS_EXEC_WARNINGS template @@ -86,7 +86,7 @@ ArrayPortalToIteratorBegin(const PortalType& portal) return iterators.GetBegin(); } -/// Convienience function for converting an ArrayPortal to an end iterator. +/// Convenience function for converting an ArrayPortal to an end iterator. /// VTKM_SUPPRESS_EXEC_WARNINGS template diff --git a/vtkm/cont/ArrayRangeCompute.cxx b/vtkm/cont/ArrayRangeCompute.cxx index f60c24f75..540a54588 100644 --- a/vtkm/cont/ArrayRangeCompute.cxx +++ b/vtkm/cont/ArrayRangeCompute.cxx @@ -25,6 +25,11 @@ namespace vtkm namespace cont { +void ThrowArrayRangeComputeFailed() +{ + throw vtkm::cont::ErrorExecution("Failed to run ArrayRangeComputation on any device."); +} + #define VTKM_ARRAY_RANGE_COMPUTE_IMPL_T(T, Storage) \ VTKM_CONT \ vtkm::cont::ArrayHandle ArrayRangeCompute( \ diff --git a/vtkm/cont/ArrayRangeCompute.h b/vtkm/cont/ArrayRangeCompute.h index c293b0a0f..9c5c492ce 100644 --- a/vtkm/cont/ArrayRangeCompute.h +++ b/vtkm/cont/ArrayRangeCompute.h @@ -159,6 +159,8 @@ VTKM_CONT inline vtkm::cont::ArrayHandle ArrayRangeCompute( return result; } + +VTKM_CONT_EXPORT void ThrowArrayRangeComputeFailed(); } } // namespace vtkm::cont diff --git a/vtkm/cont/ArrayRangeCompute.hxx b/vtkm/cont/ArrayRangeCompute.hxx index 1dd6c471e..ff480ea9a 100644 --- a/vtkm/cont/ArrayRangeCompute.hxx +++ b/vtkm/cont/ArrayRangeCompute.hxx @@ -25,8 +25,9 @@ #include #include -#include -#include +#include + +#include namespace vtkm { @@ -36,73 +37,68 @@ namespace cont namespace detail { -template struct ArrayRangeComputeFunctor { - VTKM_IS_ARRAY_HANDLE(ArrayHandleType); - - ArrayHandleType InputArray; - vtkm::cont::ArrayHandle RangeArray; - - VTKM_CONT - ArrayRangeComputeFunctor(const ArrayHandleType& input) - : InputArray(input) - { - } - - template - VTKM_CONT bool operator()(Device) + template + VTKM_CONT bool operator()(Device, + const vtkm::cont::ArrayHandle& handle, + const vtkm::Vec& initialValue, + vtkm::Vec& result) const { VTKM_IS_DEVICE_ADAPTER_TAG(Device); - - using ValueType = typename ArrayHandleType::ValueType; - using VecTraits = vtkm::VecTraits; - const vtkm::IdComponent NumberOfComponents = VecTraits::NUM_COMPONENTS; - using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; - - this->RangeArray.Allocate(NumberOfComponents); - - if (this->InputArray.GetNumberOfValues() < 1) - { - for (vtkm::IdComponent i = 0; i < NumberOfComponents; ++i) - { - this->RangeArray.GetPortalControl().Set(i, vtkm::Range()); - } - return true; - } - - vtkm::Vec initial(this->InputArray.GetPortalConstControl().Get(0)); - - vtkm::Vec result = - Algorithm::Reduce(this->InputArray, initial, vtkm::MinAndMax()); - - for (vtkm::IdComponent i = 0; i < NumberOfComponents; ++i) - { - this->RangeArray.GetPortalControl().Set( - i, - vtkm::Range(VecTraits::GetComponent(result[0], i), VecTraits::GetComponent(result[1], i))); - } - + result = Algorithm::Reduce(handle, initialValue, vtkm::MinAndMax()); return true; } }; -template +template inline vtkm::cont::ArrayHandle ArrayRangeComputeImpl( - const ArrayHandleType& input, - vtkm::cont::RuntimeDeviceTracker tracker) + const vtkm::cont::ArrayHandle& input, + vtkm::cont::RuntimeDeviceTracker& tracker) { - VTKM_IS_ARRAY_HANDLE(ArrayHandleType); + using VecTraits = vtkm::VecTraits; + using CT = typename VecTraits::ComponentType; + //We want to minimize the amount of code that we do in try execute as + //it is repeated for each + vtkm::cont::ArrayHandle range; + range.Allocate(VecTraits::NUM_COMPONENTS); - detail::ArrayRangeComputeFunctor functor(input); - - if (!vtkm::cont::TryExecute(functor, tracker)) + if (input.GetNumberOfValues() < 1) { - throw vtkm::cont::ErrorExecution("Failed to run ArrayRangeComputation on any device."); + auto portal = range.GetPortalControl(); + for (vtkm::IdComponent i = 0; i < VecTraits::NUM_COMPONENTS; ++i) + { + portal.Set(i, vtkm::Range()); + } } + else + { + //We used the limits, so that we don't need to sync the array handle + // + vtkm::Vec result; + vtkm::Vec initial; + initial[0] = T(std::numeric_limits::max()); + initial[1] = T(std::numeric_limits::lowest()); - return functor.RangeArray; + const bool rangeComputed = + vtkm::cont::TryExecute(detail::ArrayRangeComputeFunctor{}, tracker, input, initial, result); + if (!rangeComputed) + { + ThrowArrayRangeComputeFailed(); + } + else + { + auto portal = range.GetPortalControl(); + for (vtkm::IdComponent i = 0; i < VecTraits::NUM_COMPONENTS; ++i) + { + portal.Set(i, + vtkm::Range(VecTraits::GetComponent(result[0], i), + VecTraits::GetComponent(result[1], i))); + } + } + } + return range; } } // namespace detail @@ -113,7 +109,6 @@ inline vtkm::cont::ArrayHandle ArrayRangeCompute( vtkm::cont::RuntimeDeviceTracker tracker) { VTKM_IS_ARRAY_HANDLE(ArrayHandleType); - return detail::ArrayRangeComputeImpl(input, tracker); } } diff --git a/vtkm/cont/CMakeLists.txt b/vtkm/cont/CMakeLists.txt index c9412961f..051bc86df 100644 --- a/vtkm/cont/CMakeLists.txt +++ b/vtkm/cont/CMakeLists.txt @@ -107,6 +107,7 @@ set(sources Field.cxx internal/SimplePolymorphicContainer.cxx internal/ArrayManagerExecutionShareWithControl.cxx + internal/ArrayHandleBasicImpl.cxx StorageBasic.cxx ) diff --git a/vtkm/cont/CellLocator.h b/vtkm/cont/CellLocator.h index 6be442faa..b55da1ef4 100644 --- a/vtkm/cont/CellLocator.h +++ b/vtkm/cont/CellLocator.h @@ -38,7 +38,7 @@ private: VTKM_CONT static bool IsUniformGrid(const vtkm::cont::DynamicCellSet& cellset, const vtkm::cont::CoordinateSystem& coordinates) { - return coordinates.GetData().IsSameType() && + return coordinates.GetData().IsType() && (cellset.IsType>() || cellset.IsType>() || cellset.IsType>()); @@ -97,7 +97,7 @@ public: "expecting ArrayHandleUniformPointCoordinates for coordinates"); auto cellId3 = static_cast((point - coords.GetOrigin()) / coords.GetSpacing()); - auto cellDim = coords.GetDimensions() - vtkm::Id3(1); + auto cellDim = vtkm::Max(vtkm::Id3(1), coords.GetDimensions() - vtkm::Id3(1)); if (cellId3[0] < 0 || cellId3[0] >= cellDim[0] || cellId3[1] < 0 || cellId3[1] >= cellDim[1] || cellId3[2] < 0 || cellId3[2] >= cellDim[2]) { diff --git a/vtkm/cont/DeviceAdapterAlgorithm.h b/vtkm/cont/DeviceAdapterAlgorithm.h index 588f6f598..9454244bd 100644 --- a/vtkm/cont/DeviceAdapterAlgorithm.h +++ b/vtkm/cont/DeviceAdapterAlgorithm.h @@ -439,6 +439,26 @@ struct DeviceAdapterAlgorithm /// VTKM_CONT static void Synchronize(); + /// \brief Apply a given binary operation function element-wise to input arrays. + /// + /// Apply the give binary operation to pairs of elements from the two input array + /// \c input1 and \c input2. The number of elements in the input arrays do not + /// have to be the same, in this case, only the smaller of the two numbers of elements + /// will be applied. + /// Outputs of the binary operation is stored in \c output. + /// + template + VTKM_CONT static void Transform(const vtkm::cont::ArrayHandle& input1, + const vtkm::cont::ArrayHandle& input2, + vtkm::cont::ArrayHandle& output, + BinaryFunctor binaryFunctor); + /// \brief Reduce an array to only the unique values it contains /// /// Removes all duplicate values in \c values that are adjacent to each @@ -611,7 +631,7 @@ class DeviceAdapterAtomicArrayImplementation; /// \brief Class providing a device-specific support for selecting the optimal /// Task type for a given worklet. /// -/// When worklets are launched inside the execution enviornment we need to +/// When worklets are launched inside the execution environment we need to /// ask the device adapter what is the preferred execution style, be it /// a tiled iteration pattern, or strided. This class /// diff --git a/vtkm/cont/DynamicArrayHandle.h b/vtkm/cont/DynamicArrayHandle.h index bae63cd24..1d8d0b215 100644 --- a/vtkm/cont/DynamicArrayHandle.h +++ b/vtkm/cont/DynamicArrayHandle.h @@ -67,7 +67,7 @@ struct VTKM_CONT_EXPORT PolymorphicArrayHandleContainerBase /// /// The \c PolymorphicArrayHandleContainer is similar to the /// \c SimplePolymorphicContainer in that it can contain an object of an -/// unkown type. However, this class specifically holds ArrayHandle objects +/// unknown type. However, this class specifically holds ArrayHandle objects /// (with different template parameters) so that it can polymorphically answer /// simple questions about the object. /// @@ -289,7 +289,7 @@ public: return this->CastToTypeStorage(); } - /// Given a refernce to an ArrayHandle object, casts this array to the + /// Given a references to an ArrayHandle object, casts this array to the /// ArrayHandle's type and sets the given ArrayHandle to this array. Throws /// \c ErrorBadType if the cast does not work. Use \c /// ArrayHandleType to check if the cast can happen. diff --git a/vtkm/cont/Field.h b/vtkm/cont/Field.h index ee659c295..78c7199eb 100644 --- a/vtkm/cont/Field.h +++ b/vtkm/cont/Field.h @@ -308,7 +308,7 @@ void CastAndCall(const vtkm::cont::Field& field, Functor&& f, Args&&... args) } //@{ -/// Convinience functions to build fields from C style arrays and std::vector +/// Convenience functions to build fields from C style arrays and std::vector template vtkm::cont::Field make_Field(std::string name, Field::AssociationEnum association, diff --git a/vtkm/cont/MultiBlock.h b/vtkm/cont/MultiBlock.h index 3261cb3ec..6b732c336 100644 --- a/vtkm/cont/MultiBlock.h +++ b/vtkm/cont/MultiBlock.h @@ -36,16 +36,16 @@ namespace cont class VTKM_CONT_EXPORT MultiBlock { public: - /// creat a new MultiBlcok containng a single DataSet "ds" + /// create a new MultiBlock containng a single DataSet "ds" VTKM_CONT MultiBlock(const vtkm::cont::DataSet& ds); - /// creat a new MultiBlcok with the exisiting one "src" + /// create a new MultiBlock with the existing one "src" VTKM_CONT MultiBlock(const vtkm::cont::MultiBlock& src); - /// creat a new MultiBlcok with a DataSet vector "mblocks" + /// create a new MultiBlock with a DataSet vector "mblocks" VTKM_CONT MultiBlock(const std::vector& mblocks); - /// creat a new MultiBlcok with the capacity set to be "size" + /// create a new MultiBlock with the capacity set to be "size" VTKM_CONT MultiBlock(vtkm::Id size); @@ -57,7 +57,7 @@ public: VTKM_CONT ~MultiBlock(); - /// get the field "field_name" from blcok "block_index" + /// get the field "field_name" from block "block_index" VTKM_CONT vtkm::cont::Field GetField(const std::string& field_name, const int& block_index); diff --git a/vtkm/cont/PointLocatorUniformGrid.h b/vtkm/cont/PointLocatorUniformGrid.h index 4af29b451..73e8d5f5c 100644 --- a/vtkm/cont/PointLocatorUniformGrid.h +++ b/vtkm/cont/PointLocatorUniformGrid.h @@ -175,7 +175,7 @@ public: template void Build(const vtkm::cont::ArrayHandle>& coords, DeviceAdapter) { - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; // generate unique id for each input point vtkm::cont::ArrayHandleCounting pointCounting(0, 1, coords.GetNumberOfValues()); Algorithm::Copy(pointCounting, PointIds); diff --git a/vtkm/cont/RuntimeDeviceTracker.h b/vtkm/cont/RuntimeDeviceTracker.h index bd873076c..a83902bb5 100644 --- a/vtkm/cont/RuntimeDeviceTracker.h +++ b/vtkm/cont/RuntimeDeviceTracker.h @@ -131,7 +131,7 @@ public: /// /// If you want a \c RuntimeDeviceTracker with independent state, just create /// one independently. If you want to start with the state of a source - /// \c RuntimeDeviceTracker but update the state indepenently, you can use + /// \c RuntimeDeviceTracker but update the state independently, you can use /// \c DeepCopy method to get the initial state. Further changes will /// not be shared. /// @@ -152,7 +152,7 @@ public: /// /// If you want a \c RuntimeDeviceTracker with independent state, just create /// one independently. If you want to start with the state of a source - /// \c RuntimeDeviceTracker but update the state indepenently, you can use + /// \c RuntimeDeviceTracker but update the state independently, you can use /// \c DeepCopy method to get the initial state. Further changes will /// not be shared. /// diff --git a/vtkm/cont/Storage.h b/vtkm/cont/Storage.h index d30b9815a..43fae45e3 100644 --- a/vtkm/cont/Storage.h +++ b/vtkm/cont/Storage.h @@ -132,7 +132,7 @@ public: VTKM_CONT PortalConstType GetPortalConst() const; - /// Retuns the number of entries allocated in the array. + /// Returns the number of entries allocated in the array. VTKM_CONT vtkm::Id GetNumberOfValues() const; diff --git a/vtkm/cont/StorageBasic.cxx b/vtkm/cont/StorageBasic.cxx index 84f111237..d833cd1df 100644 --- a/vtkm/cont/StorageBasic.cxx +++ b/vtkm/cont/StorageBasic.cxx @@ -20,6 +20,7 @@ #define vtkm_cont_StorageBasic_cxx #include +#include #if defined(VTKM_POSIX) #define VTKM_MEMALIGN_POSIX @@ -51,11 +52,7 @@ namespace cont namespace internal { -StorageBasicBase::~StorageBasicBase() -{ -} - -void* alloc_aligned(size_t size, size_t align) +void* StorageBasicAllocator::allocate(size_t size, size_t align) { #if defined(VTKM_MEMALIGN_POSIX) void* mem = nullptr; @@ -70,14 +67,10 @@ void* alloc_aligned(size_t size, size_t align) #else void* mem = malloc(size); #endif - if (mem == nullptr) - { - throw std::bad_alloc(); - } return mem; } -void free_aligned(void* mem) +void StorageBasicAllocator::free_memory(void* mem) { #if defined(VTKM_MEMALIGN_POSIX) free(mem); @@ -90,33 +83,188 @@ void free_aligned(void* mem) #endif } -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; +StorageBasicBase::StorageBasicBase() + : Array(nullptr) + , AllocatedByteSize(0) + , NumberOfValues(0) + , DeallocateOnRelease(true) +{ +} -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; +StorageBasicBase::StorageBasicBase(const void* array, + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) + : Array(const_cast(array)) + , AllocatedByteSize(static_cast(numberOfValues) * sizeOfValue) + , NumberOfValues(numberOfValues) + , DeallocateOnRelease(array == nullptr ? true : false) +{ +} -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; -template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; +StorageBasicBase::~StorageBasicBase() +{ + this->ReleaseResources(); +} + +StorageBasicBase::StorageBasicBase(const StorageBasicBase& src) + : Array(src.Array) + , AllocatedByteSize(src.AllocatedByteSize) + , NumberOfValues(src.NumberOfValues) + , DeallocateOnRelease(src.DeallocateOnRelease) + +{ + if (src.DeallocateOnRelease) + { + throw vtkm::cont::ErrorBadValue( + "Attempted to copy a storage array that needs deallocation. " + "This is disallowed to prevent complications with deallocation."); + } +} + +StorageBasicBase StorageBasicBase::operator=(const StorageBasicBase& src) +{ + if (src.DeallocateOnRelease) + { + throw vtkm::cont::ErrorBadValue( + "Attempted to copy a storage array that needs deallocation. " + "This is disallowed to prevent complications with deallocation."); + } + + this->ReleaseResources(); + this->Array = src.Array; + this->AllocatedByteSize = src.AllocatedByteSize; + this->NumberOfValues = src.NumberOfValues; + this->DeallocateOnRelease = src.DeallocateOnRelease; + return *this; +} + +void StorageBasicBase::ReleaseResources() +{ + if (this->AllocatedByteSize > 0) + { + VTKM_ASSERT(this->Array != nullptr); + if (this->DeallocateOnRelease) + { + AllocatorType{}.free_memory(this->Array); + } + this->Array = nullptr; + this->AllocatedByteSize = 0; + this->NumberOfValues = 0; + } + else + { + VTKM_ASSERT(this->Array == nullptr); + } +} + +void StorageBasicBase::AllocateValues(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfValue) +{ + if (numberOfValues < 0) + { + throw vtkm::cont::ErrorBadAllocation("Cannot allocate an array with negative size."); + } + + // Check that the number of bytes won't be more than a size_t can hold. + const size_t maxNumValues = std::numeric_limits::max() / sizeOfValue; + if (static_cast(numberOfValues) > maxNumValues) + { + throw ErrorBadAllocation("Requested allocation exceeds size_t capacity."); + } + + // If we are allocating less data, just shrink the array. + // (If allocation empty, drop down so we can deallocate memory.) + vtkm::UInt64 allocsize = static_cast(numberOfValues) * sizeOfValue; + if ((allocsize <= this->AllocatedByteSize) && (numberOfValues > 0)) + { + this->NumberOfValues = numberOfValues; + return; + } + + if (!this->DeallocateOnRelease) + { + throw vtkm::cont::ErrorBadValue("User allocated arrays cannot be reallocated."); + } + + this->ReleaseResources(); + + if (numberOfValues > 0) + { + this->Array = AllocatorType{}.allocate(allocsize, VTKM_ALLOCATION_ALIGNMENT); + this->AllocatedByteSize = allocsize; + this->NumberOfValues = numberOfValues; + if (this->Array == nullptr) + { + // Make sureour state is OK. + this->AllocatedByteSize = 0; + this->NumberOfValues = 0; + throw vtkm::cont::ErrorBadAllocation("Could not allocate basic control array."); + } + } + else + { + // ReleaseResources should have already set NumberOfValues to 0. + VTKM_ASSERT(this->NumberOfValues == 0); + VTKM_ASSERT(this->AllocatedByteSize == 0); + } + this->DeallocateOnRelease = true; +} + +void StorageBasicBase::Shrink(vtkm::Id numberOfValues) +{ + if (numberOfValues > this->NumberOfValues) + { + throw vtkm::cont::ErrorBadValue("Shrink method cannot be used to grow array."); + } + + this->NumberOfValues = numberOfValues; +} + +void* StorageBasicBase::GetBasePointer() const +{ + return this->Array; +} + +void* StorageBasicBase::GetEndPointer(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfValue) const +{ + VTKM_ASSERT(this->NumberOfValues == numberOfValues); + if (!this->Array) + { + return nullptr; + } + + auto p = static_cast(this->Array); + auto offset = static_cast(this->NumberOfValues) * sizeOfValue; + return static_cast(p + offset); +} + +void* StorageBasicBase::GetCapacityPointer() const +{ + if (!this->Array) + { + return nullptr; + } + auto v = static_cast(this->Array) + AllocatedByteSize; + return static_cast(v); +} + +#define _VTKM_STORAGE_INSTANTIATE(Type) \ + template class VTKM_CONT_EXPORT Storage; \ + template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; \ + template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; \ + template class VTKM_CONT_EXPORT Storage, StorageTagBasic>; + +_VTKM_STORAGE_INSTANTIATE(char) +_VTKM_STORAGE_INSTANTIATE(vtkm::Int8) +_VTKM_STORAGE_INSTANTIATE(vtkm::UInt8) +_VTKM_STORAGE_INSTANTIATE(vtkm::Int16) +_VTKM_STORAGE_INSTANTIATE(vtkm::UInt16) +_VTKM_STORAGE_INSTANTIATE(vtkm::Int32) +_VTKM_STORAGE_INSTANTIATE(vtkm::UInt32) +_VTKM_STORAGE_INSTANTIATE(vtkm::Int64) +_VTKM_STORAGE_INSTANTIATE(vtkm::UInt64) +_VTKM_STORAGE_INSTANTIATE(vtkm::Float32) +_VTKM_STORAGE_INSTANTIATE(vtkm::Float64) } } } // namespace vtkm::cont::internal diff --git a/vtkm/cont/StorageBasic.h b/vtkm/cont/StorageBasic.h index 2d362bce2..835c1d692 100644 --- a/vtkm/cont/StorageBasic.h +++ b/vtkm/cont/StorageBasic.h @@ -28,11 +28,6 @@ #include -// Defines the cache line size in bytes to align allocations to -#ifndef VTKM_CACHE_LINE_SIZE -#define VTKM_CACHE_LINE_SIZE 64 -#endif - namespace vtkm { namespace cont @@ -46,126 +41,87 @@ struct VTKM_ALWAYS_EXPORT StorageTagBasic namespace internal { -VTKM_CONT_EXPORT -void* alloc_aligned(size_t size, size_t align); - -VTKM_CONT_EXPORT -void free_aligned(void* mem); - -/// \brief an aligned allocator -/// A simple aligned allocator type that will align allocations to `Alignment` bytes -/// TODO: Once C++11 std::allocator_traits is better used by STL and we want to drop -/// support for pre-C++11 we can drop a lot of the typedefs and functions here. -template -struct AlignedAllocator +/// Class that does all of VTK-m allocations +/// for storage basic. This is exists so that +/// stolen arrays can call the correct free +/// function ( _aligned_malloc ) on windows +struct VTKM_CONT_EXPORT StorageBasicAllocator { - using value_type = T; - using reference = T&; - using const_reference = const T&; - using pointer = T*; - using const_pointer = const T*; - using void_pointer = void*; - using const_void_pointer = const void*; - using difference_type = std::ptrdiff_t; - using size_type = std::size_t; + void* allocate(size_t size, size_t align); + void free_memory(void* p); - template - struct rebind + template + void deallocate(T* p) { - using other = AlignedAllocator; - }; - - AlignedAllocator() {} - - template - AlignedAllocator(const AlignedAllocator&) - { - } - - pointer allocate(size_t n) - { - return static_cast(alloc_aligned(n * sizeof(T), Alignment)); - } - void deallocate(pointer p, size_t) { free_aligned(static_cast(p)); } - pointer address(reference r) { return &r; } - const_pointer address(const_reference r) { return &r; } - size_type max_size() const { return (std::numeric_limits::max)() / sizeof(T); } - void construct(pointer p, const T& t) - { - (void)p; - new (p) T(t); - } - void destroy(pointer p) - { - (void)p; - p->~T(); + this->free_memory(static_cast(p)); } }; - -template -bool operator==(const AlignedAllocator&, const AlignedAllocator&) -{ - return AlignA == AlignB; -} -template -bool operator!=(const AlignedAllocator&, const AlignedAllocator&) -{ - return AlignA != AlignB; -} - -/// Base class for basic storage classes. This is currently only used by -/// Basic storage to provide a type-agnostic API for allocations, etc. +/// Base class for basic storage classes. This allow us to implement +/// vtkm::cont::Storage for any T type with no overhead +/// as all heavy logic is provide by a type-agnostic API including allocations, etc. class VTKM_CONT_EXPORT StorageBasicBase { public: - StorageBasicBase() {} - virtual ~StorageBasicBase(); + using AllocatorType = StorageBasicAllocator; + VTKM_CONT StorageBasicBase(); + VTKM_CONT StorageBasicBase(const void* array, vtkm::Id size, vtkm::UInt64 sizeOfValue); + VTKM_CONT ~StorageBasicBase(); - /// \brief Return the number of bytes allocated for this storage object. - VTKM_CONT - virtual vtkm::UInt64 GetNumberOfBytes() const = 0; + VTKM_CONT StorageBasicBase(const StorageBasicBase& src); + VTKM_CONT StorageBasicBase operator=(const StorageBasicBase& src); - /// \brief Allocates an array with the specified size in bytes. + /// \brief Return the number of bytes allocated for this storage object(Capacity). + /// + /// + VTKM_CONT vtkm::UInt64 GetNumberOfBytes() const { return this->AllocatedByteSize; } + + /// \brief Return the number of 'T' values allocated by this storage + VTKM_CONT vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; } + + /// \brief Allocates an array with the specified number of elements. /// /// The allocation may be done on an already existing array, but can wipe out /// any data already in the array. This method can throw /// ErrorBadAllocation if the array cannot be allocated or /// ErrorBadValue if the allocation is not feasible (for example, the /// array storage is read-only). - VTKM_CONT - virtual void AllocateBytes(vtkm::UInt64 numberOfBytes) = 0; + VTKM_CONT void AllocateValues(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfValue); /// \brief Reduces the size of the array without changing its values. /// /// This method allows you to resize the array without reallocating it. The - /// size of the array is changed to \c numberOfBytes bytes. The data - /// in the reallocated array stays the same, but \c numberOfBytes must be + /// size of the array is changed so that it can hold \c numberOfValues values. + /// The data in the reallocated array stays the same, but \c numberOfValues must be /// equal or less than the preexisting size. That is, this method can only be /// used to shorten the array, not lengthen. - VTKM_CONT - virtual void ShrinkBytes(vtkm::UInt64 numberOfBytes) = 0; + VTKM_CONT void Shrink(vtkm::Id numberOfValues); /// \brief Frees any resources (i.e. memory) stored in this array. /// /// After calling this method GetNumberOfBytes() will return 0. The /// resources should also be released when the Storage class is /// destroyed. - VTKM_CONT - virtual void ReleaseResources() = 0; + VTKM_CONT void ReleaseResources(); + + /// \brief Returns if vtkm will deallocate this memory. VTK-m StorageBasic + /// is designed that VTK-m will not deallocate user passed memory, or + /// instances that have been stolen (\c StealArray) + VTKM_CONT bool WillDeallocate() const { return this->DeallocateOnRelease; } /// Return the memory location of the first element of the array data. - VTKM_CONT - virtual void* GetBasePointer() const = 0; + VTKM_CONT void* GetBasePointer() const; - /// Return the memory location of the first element past the end of the array - /// data. - VTKM_CONT - virtual void* GetEndPointer() const = 0; + VTKM_CONT void* GetEndPointer(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfValue) const; /// Return the memory location of the first element past the end of the /// array's allocated memory buffer. - VTKM_CONT - virtual void* GetCapacityPointer() const = 0; + VTKM_CONT void* GetCapacityPointer() const; + +protected: + void* Array; + vtkm::UInt64 AllocatedByteSize; + vtkm::Id NumberOfValues; + bool DeallocateOnRelease; }; /// A basic implementation of an Storage object. @@ -180,70 +136,23 @@ template class VTKM_ALWAYS_EXPORT Storage : public StorageBasicBase { public: + using AllocatorType = vtkm::cont::internal::StorageBasicAllocator; using ValueType = ValueT; using PortalType = vtkm::cont::internal::ArrayPortalFromIterators; using PortalConstType = vtkm::cont::internal::ArrayPortalFromIterators; - /// The original design of this class provided an allocator as a template - /// parameters. That messed things up, though, because other templated - /// classes assume that the \c Storage has one template parameter. There are - /// other ways to allow you to specify the allocator, but it is uncertain - /// whether that would ever be useful. So, instead of jumping through hoops - /// implementing them, just fix the allocator for now. - /// - using AllocatorType = AlignedAllocator; - public: /// \brief construct storage that VTK-m is responsible for - VTKM_CONT - Storage(); + VTKM_CONT Storage(); /// \brief construct storage that VTK-m is not responsible for - VTKM_CONT - Storage(const ValueType* array, vtkm::Id numberOfValues = 0); + VTKM_CONT Storage(const ValueType* array, vtkm::Id numberOfValues = 0); - VTKM_CONT - ~Storage(); + VTKM_CONT void Allocate(vtkm::Id numberOfValues); - VTKM_CONT - Storage(const Storage& src); + VTKM_CONT PortalType GetPortal(); - VTKM_CONT - Storage& operator=(const Storage& src); - - VTKM_CONT - void ReleaseResources() final; - - VTKM_CONT - void Allocate(vtkm::Id numberOfValues); - - VTKM_CONT - vtkm::Id GetNumberOfValues() const { return this->NumberOfValues; } - - VTKM_CONT - vtkm::UInt64 GetNumberOfBytes() const final - { - return static_cast(this->NumberOfValues) * - static_cast(sizeof(ValueT)); - } - - VTKM_CONT - void Shrink(vtkm::Id numberOfValues); - - VTKM_CONT - void AllocateBytes(vtkm::UInt64) final; - - VTKM_CONT - void ShrinkBytes(vtkm::UInt64) final; - - VTKM_CONT - PortalType GetPortal() { return PortalType(this->Array, this->Array + this->NumberOfValues); } - - VTKM_CONT - PortalConstType GetPortalConst() const - { - return PortalConstType(this->Array, this->Array + this->NumberOfValues); - } + VTKM_CONT PortalConstType GetPortalConst() const; /// \brief Get a pointer to the underlying data structure. /// @@ -251,10 +160,9 @@ public: /// memory associated with this array still belongs to the Storage (i.e. /// Storage will eventually deallocate the array). /// - VTKM_CONT - ValueType* GetArray() { return this->Array; } - VTKM_CONT - const ValueType* GetArray() const { return this->Array; } + VTKM_CONT ValueType* GetArray(); + + VTKM_CONT const ValueType* GetArray() const; /// \brief Take the reference away from this object. /// @@ -265,36 +173,7 @@ public: /// VTK-m and not having to keep a VTK-m object around. Obviously the caller /// becomes responsible for destroying the memory. /// - VTKM_CONT - ValueType* StealArray(); - - /// \brief Returns if vtkm will deallocate this memory. VTK-m StorageBasic - /// is designed that VTK-m will not deallocate user passed memory, or - /// instances that have been stolen (\c StealArray) - VTKM_CONT - bool WillDeallocate() const { return this->DeallocateOnRelease; } - - - VTKM_CONT - void* GetBasePointer() const final { return static_cast(this->Array); } - - VTKM_CONT - void* GetEndPointer() const final - { - return static_cast(this->Array + this->NumberOfValues); - } - - VTKM_CONT - void* GetCapacityPointer() const final - { - return static_cast(this->Array + this->AllocatedSize); - } - -private: - ValueType* Array; - vtkm::Id NumberOfValues; - vtkm::Id AllocatedSize; - bool DeallocateOnRelease; + VTKM_CONT ValueType* StealArray(); }; } // namespace internal @@ -311,39 +190,23 @@ namespace internal /// \cond /// Make doxygen ignore this section -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; +#define _VTKM_STORAGE_EXPORT(Type) \ + extern template class VTKM_CONT_TEMPLATE_EXPORT Storage; \ + extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; \ + extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; \ + extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; - -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; - -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; -extern template class VTKM_CONT_TEMPLATE_EXPORT - Storage, StorageTagBasic>; +_VTKM_STORAGE_EXPORT(char) +_VTKM_STORAGE_EXPORT(vtkm::Int8) +_VTKM_STORAGE_EXPORT(vtkm::UInt8) +_VTKM_STORAGE_EXPORT(vtkm::Int16) +_VTKM_STORAGE_EXPORT(vtkm::UInt16) +_VTKM_STORAGE_EXPORT(vtkm::Int32) +_VTKM_STORAGE_EXPORT(vtkm::UInt32) +_VTKM_STORAGE_EXPORT(vtkm::Int64) +_VTKM_STORAGE_EXPORT(vtkm::UInt64) +_VTKM_STORAGE_EXPORT(vtkm::Float32) +_VTKM_STORAGE_EXPORT(vtkm::Float64) /// \endcond } } diff --git a/vtkm/cont/StorageBasic.hxx b/vtkm/cont/StorageBasic.hxx index 6d9ec4249..24d84d684 100644 --- a/vtkm/cont/StorageBasic.hxx +++ b/vtkm/cont/StorageBasic.hxx @@ -31,173 +31,55 @@ namespace internal template Storage::Storage() - : Array(nullptr) - , NumberOfValues(0) - , AllocatedSize(0) - , DeallocateOnRelease(true) + : StorageBasicBase() { } template Storage::Storage(const T* array, vtkm::Id numberOfValues) - : Array(const_cast(array)) - , NumberOfValues(numberOfValues) - , AllocatedSize(numberOfValues) - , DeallocateOnRelease(array == nullptr ? true : false) + : StorageBasicBase(const_cast(array), numberOfValues, sizeof(T)) { } -template -Storage::~Storage() -{ - this->ReleaseResources(); -} - -template -Storage::Storage(const Storage& src) - : Array(src.Array) - , NumberOfValues(src.NumberOfValues) - , AllocatedSize(src.AllocatedSize) - , DeallocateOnRelease(src.DeallocateOnRelease) -{ - if (src.DeallocateOnRelease) - { - throw vtkm::cont::ErrorBadValue( - "Attempted to copy a storage array that needs deallocation. " - "This is disallowed to prevent complications with deallocation."); - } -} - -template -Storage& Storage::operator=( - const Storage& src) -{ - if (src.DeallocateOnRelease) - { - throw vtkm::cont::ErrorBadValue( - "Attempted to copy a storage array that needs deallocation. " - "This is disallowed to prevent complications with deallocation."); - } - - this->ReleaseResources(); - this->Array = src.Array; - this->NumberOfValues = src.NumberOfValues; - this->AllocatedSize = src.AllocatedSize; - this->DeallocateOnRelease = src.DeallocateOnRelease; - - return *this; -} - -template -void Storage::ReleaseResources() -{ - if (this->NumberOfValues > 0) - { - VTKM_ASSERT(this->Array != nullptr); - if (this->DeallocateOnRelease) - { - AllocatorType allocator; - allocator.deallocate(this->Array, static_cast(this->AllocatedSize)); - } - this->Array = nullptr; - this->NumberOfValues = 0; - this->AllocatedSize = 0; - } - else - { - VTKM_ASSERT(this->Array == nullptr); - } -} - template void Storage::Allocate(vtkm::Id numberOfValues) { - if (numberOfValues < 0) - { - throw vtkm::cont::ErrorBadAllocation("Cannot allocate an array with negative size."); - } - - // Check that the number of bytes won't be more than a size_t can hold. - const size_t maxNumValues = std::numeric_limits::max() / sizeof(T); - if (static_cast(numberOfValues) > static_cast(maxNumValues)) - { - throw ErrorBadAllocation("Requested allocation exceeds size_t capacity."); - } - this->AllocateBytes(static_cast(numberOfValues) * - static_cast(sizeof(T))); + this->AllocateValues(numberOfValues, sizeof(T)); } template -void Storage::AllocateBytes(vtkm::UInt64 numberOfBytes) +typename Storage::PortalType +Storage::GetPortal() { - const vtkm::Id numberOfValues = - static_cast(numberOfBytes / static_cast(sizeof(T))); - - // If we are allocating less data, just shrink the array. - // (If allocation empty, drop down so we can deallocate memory.) - if ((numberOfValues <= this->AllocatedSize) && (numberOfValues > 0)) - { - this->NumberOfValues = numberOfValues; - return; - } - - if (!this->DeallocateOnRelease) - { - throw vtkm::cont::ErrorBadValue("User allocated arrays cannot be reallocated."); - } - - this->ReleaseResources(); - try - { - if (numberOfValues > 0) - { - AllocatorType allocator; - this->Array = allocator.allocate(static_cast(numberOfValues)); - this->AllocatedSize = numberOfValues; - this->NumberOfValues = numberOfValues; - } - else - { - // ReleaseResources should have already set AllocatedSize to 0. - VTKM_ASSERT(this->AllocatedSize == 0); - } - } - catch (std::bad_alloc&) - { - // Make sureour state is OK. - this->Array = nullptr; - this->NumberOfValues = 0; - this->AllocatedSize = 0; - throw vtkm::cont::ErrorBadAllocation("Could not allocate basic control array."); - } - - this->DeallocateOnRelease = true; + auto v = static_cast(this->Array); + return PortalType(v, v + this->NumberOfValues); } template -void Storage::Shrink(vtkm::Id numberOfValues) +typename Storage::PortalConstType +Storage::GetPortalConst() const { - this->ShrinkBytes(static_cast(numberOfValues) * - static_cast(sizeof(T))); + auto v = static_cast(this->Array); + return PortalConstType(v, v + this->NumberOfValues); } template -void Storage::ShrinkBytes(vtkm::UInt64 numberOfBytes) +T* Storage::GetArray() { - if (numberOfBytes > this->GetNumberOfBytes()) - { - throw vtkm::cont::ErrorBadValue("Shrink method cannot be used to grow array."); - } + return static_cast(this->Array); +} - this->NumberOfValues = - static_cast(numberOfBytes / static_cast(sizeof(T))); +template +const T* Storage::GetArray() const +{ + return static_cast(this->Array); } template T* Storage::StealArray() { this->DeallocateOnRelease = false; - return this->Array; + return static_cast(this->Array); } } // namespace internal diff --git a/vtkm/cont/Timer.h b/vtkm/cont/Timer.h index c6dda867a..ac2182dba 100644 --- a/vtkm/cont/Timer.h +++ b/vtkm/cont/Timer.h @@ -27,7 +27,7 @@ namespace vtkm namespace cont { -/// A class that can be used to time operations in VTK-m that might be occuring +/// A class that can be used to time operations in VTK-m that might be occurring /// in parallel. You should make sure that the device adapter for the timer /// matches that being used to execute algorithms to ensure that the thread /// synchronization is correct. diff --git a/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.cu b/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.cu index 5118ee02f..d375b9f95 100644 --- a/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.cu +++ b/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.cu @@ -21,182 +21,11 @@ #define vtk_m_cont_cuda_internal_ArrayManagerExecutionCuda_cu #include -#include - -using vtkm::cont::cuda::internal::CudaAllocator; namespace vtkm { namespace cont { -namespace internal -{ - -ExecutionArrayInterfaceBasic::ExecutionArrayInterfaceBasic( - StorageBasicBase& storage) - : Superclass(storage) -{ -} - -DeviceAdapterId ExecutionArrayInterfaceBasic::GetDeviceId() const -{ - return VTKM_DEVICE_ADAPTER_CUDA; -} - -void ExecutionArrayInterfaceBasic::Allocate(TypelessExecutionArray& execArray, - vtkm::UInt64 numBytes) const -{ - // Detect if we can reuse a device-accessible pointer from the control env: - if (CudaAllocator::IsDevicePointer(execArray.ArrayControl)) - { - const vtkm::UInt64 managedCapacity = - static_cast(static_cast(execArray.ArrayControlCapacity) - - static_cast(execArray.ArrayControl)); - if (managedCapacity >= numBytes) - { - if (execArray.Array && execArray.Array != execArray.ArrayControl) - { - this->Free(execArray); - } - - execArray.Array = const_cast(execArray.ArrayControl); - execArray.ArrayEnd = static_cast(execArray.Array) + numBytes; - execArray.ArrayCapacity = const_cast(execArray.ArrayControlCapacity); - return; - } - } - - if (execArray.Array != nullptr) - { - const vtkm::UInt64 cap = static_cast(static_cast(execArray.ArrayCapacity) - - static_cast(execArray.Array)); - - if (cap < numBytes) - { // Current allocation too small -- free & realloc - this->Free(execArray); - } - else - { // Reuse buffer if possible: - execArray.ArrayEnd = static_cast(execArray.Array) + numBytes; - return; - } - } - - VTKM_ASSERT(execArray.Array == nullptr); - - // Attempt to allocate: - try - { - // Cast to char* so that the pointer math below will work. - char* tmp = static_cast(CudaAllocator::Allocate(static_cast(numBytes))); - execArray.Array = tmp; - execArray.ArrayEnd = tmp + numBytes; - execArray.ArrayCapacity = tmp + numBytes; - } - catch (const std::exception& error) - { - std::ostringstream err; - err << "Failed to allocate " << numBytes << " bytes on device: " << error.what(); - throw vtkm::cont::ErrorBadAllocation(err.str()); - } -} - -void ExecutionArrayInterfaceBasic::Free( - TypelessExecutionArray& execArray) const -{ - // If we're sharing a device-accessible pointer between control/exec, don't - // actually free it -- just null the pointers here: - if (execArray.Array == execArray.ArrayControl && - CudaAllocator::IsDevicePointer(execArray.ArrayControl)) - { - execArray.Array = nullptr; - execArray.ArrayEnd = nullptr; - execArray.ArrayCapacity = nullptr; - return; - } - - if (execArray.Array != nullptr) - { - CudaAllocator::Free(execArray.Array); - execArray.Array = nullptr; - execArray.ArrayEnd = nullptr; - execArray.ArrayCapacity = nullptr; - } -} - -void ExecutionArrayInterfaceBasic::CopyFromControl( - const void* controlPtr, - void* executionPtr, - vtkm::UInt64 numBytes) const -{ - // Do nothing if we're sharing a device-accessible pointer between control and - // execution: - if (controlPtr == executionPtr && CudaAllocator::IsDevicePointer(controlPtr)) - { - CudaAllocator::PrepareForInput(executionPtr, numBytes); - return; - } - - VTKM_CUDA_CALL(cudaMemcpyAsync(executionPtr, - controlPtr, - static_cast(numBytes), - cudaMemcpyHostToDevice, - cudaStreamPerThread)); -} - -void ExecutionArrayInterfaceBasic::CopyToControl(const void* executionPtr, - void* controlPtr, - vtkm::UInt64 numBytes) const -{ - // Do nothing if we're sharing a cuda managed pointer between control and execution: - if (controlPtr == executionPtr && CudaAllocator::IsDevicePointer(controlPtr)) - { - // If we're trying to copy a shared, non-managed device pointer back to - // control throw an exception -- the pointer cannot be read from control, - // so this operation is invalid. - if (!CudaAllocator::IsManagedPointer(controlPtr)) - { - throw vtkm::cont::ErrorBadValue( - "Control pointer is a CUDA device pointer that does not supported managed access."); - } - - // If it is managed, just return and let CUDA handle the migration for us. - CudaAllocator::PrepareForControl(controlPtr, numBytes); - return; - } - - VTKM_CUDA_CALL(cudaMemcpyAsync(controlPtr, - executionPtr, - static_cast(numBytes), - cudaMemcpyDeviceToHost, - cudaStreamPerThread)); -} - -void ExecutionArrayInterfaceBasic::UsingForRead(const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const -{ - CudaAllocator::PrepareForInput(executionPtr, static_cast(numBytes)); -} - -void ExecutionArrayInterfaceBasic::UsingForWrite(const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const -{ - CudaAllocator::PrepareForOutput(executionPtr, static_cast(numBytes)); -} - -void ExecutionArrayInterfaceBasic::UsingForReadWrite( - const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const -{ - CudaAllocator::PrepareForInPlace(executionPtr, static_cast(numBytes)); -} - - -} // end namespace internal - VTKM_INSTANTIATE_ARRAYHANDLES_FOR_DEVICE_ADAPTER(DeviceAdapterTagCuda) } } // end vtkm::cont diff --git a/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.h b/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.h index 1f77176e4..458059623 100644 --- a/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.h +++ b/vtkm/cont/cuda/internal/ArrayManagerExecutionCuda.h @@ -26,6 +26,10 @@ #include #include +//This is in a separate header so that ArrayHandleBasicImpl can include +//the interface without getting any CUDA headers +#include + // These must be placed in the vtkm::cont::internal namespace so that // the template can be found. @@ -127,49 +131,16 @@ struct ExecutionPortalFactoryBasic VTKM_CONT static PortalType CreatePortal(ValueType* start, ValueType* end) { - using ThrustPointerT = thrust::system::cuda::pointer; - ThrustPointerT startThrust(start); - ThrustPointerT endThrust(end); - return PortalType(startThrust, endThrust); + return PortalType(start, end); } VTKM_CONT static PortalConstType CreatePortalConst(const ValueType* start, const ValueType* end) { - using ThrustPointerT = thrust::system::cuda::pointer; - ThrustPointerT startThrust(start); - ThrustPointerT endThrust(end); - return PortalConstType(startThrust, endThrust); + return PortalConstType(start, end); } }; -template <> -struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic - : public ExecutionArrayInterfaceBasicBase -{ - using Superclass = ExecutionArrayInterfaceBasicBase; - - VTKM_CONT ExecutionArrayInterfaceBasic(StorageBasicBase& storage); - VTKM_CONT DeviceAdapterId GetDeviceId() const final; - VTKM_CONT void Allocate(TypelessExecutionArray& execArray, vtkm::UInt64 numBytes) const final; - VTKM_CONT void Free(TypelessExecutionArray& execArray) const final; - VTKM_CONT void CopyFromControl(const void* controlPtr, - void* executionPtr, - vtkm::UInt64 numBytes) const final; - VTKM_CONT void CopyToControl(const void* executionPtr, - void* controlPtr, - vtkm::UInt64 numBytes) const final; - - VTKM_CONT void UsingForRead(const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const final; - VTKM_CONT void UsingForWrite(const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const final; - VTKM_CONT void UsingForReadWrite(const void* controlPtr, - const void* executionPtr, - vtkm::UInt64 numBytes) const final; -}; } // namespace internal #ifndef vtk_m_cont_cuda_internal_ArrayManagerExecutionCuda_cu diff --git a/vtkm/cont/cuda/internal/ArrayManagerExecutionThrustDevice.h b/vtkm/cont/cuda/internal/ArrayManagerExecutionThrustDevice.h index a5c359f4f..6665bd609 100644 --- a/vtkm/cont/cuda/internal/ArrayManagerExecutionThrustDevice.h +++ b/vtkm/cont/cuda/internal/ArrayManagerExecutionThrustDevice.h @@ -24,21 +24,16 @@ #include #include -// Disable warnings we check vtkm for but Thrust does not. -VTKM_THIRDPARTY_PRE_INCLUDE -#include -#include -#include - -#include - -VTKM_THIRDPARTY_POST_INCLUDE - #include #include #include #include +VTKM_THIRDPARTY_PRE_INCLUDE +#include +#include +VTKM_THIRDPARTY_POST_INCLUDE + #include namespace vtkm @@ -53,15 +48,13 @@ namespace internal /// \c ArrayManagerExecutionThrustDevice provides an implementation for a \c /// ArrayManagerExecution class for a thrust device adapter that is designed /// for the cuda backend which has separate memory spaces for host and device. -/// This implementation contains a thrust::system::cuda::pointer to contain the -/// data. template class ArrayManagerExecutionThrustDevice { public: using ValueType = T; - using PointerType = typename thrust::system::cuda::pointer; - using difference_type = typename PointerType::difference_type; + using PointerType = T*; + using difference_type = std::ptrdiff_t; using StorageType = vtkm::cont::internal::Storage; @@ -71,9 +64,9 @@ public: VTKM_CONT ArrayManagerExecutionThrustDevice(StorageType* storage) : Storage(storage) - , Begin(static_cast(nullptr)) - , End(static_cast(nullptr)) - , Capacity(static_cast(nullptr)) + , Begin(nullptr) + , End(nullptr) + , Capacity(nullptr) { } @@ -83,10 +76,7 @@ public: /// Returns the size of the array. /// VTKM_CONT - vtkm::Id GetNumberOfValues() const - { - return static_cast(this->End.get() - this->Begin.get()); - } + vtkm::Id GetNumberOfValues() const { return static_cast(this->End - this->Begin); } /// Allocates the appropriate size of the array and copies the given data /// into the array. @@ -144,14 +134,13 @@ public: PortalType PrepareForOutput(vtkm::Id numberOfValues) { // Can we reuse the existing buffer? - vtkm::Id curCapacity = this->Begin.get() != nullptr - ? static_cast(this->Capacity.get() - this->Begin.get()) - : 0; + vtkm::Id curCapacity = + this->Begin != nullptr ? static_cast(this->Capacity - this->Begin) : 0; // Just mark a new end if we don't need to increase the allocation: if (curCapacity >= numberOfValues) { - this->End = PointerType(this->Begin.get() + static_cast(numberOfValues)); + this->End = this->Begin + static_cast(numberOfValues); return PortalType(this->Begin, this->End); } @@ -173,9 +162,8 @@ public: // Attempt to allocate: try { - ValueType* tmp = + this->Begin = static_cast(vtkm::cont::cuda::internal::CudaAllocator::Allocate(bufferSize)); - this->Begin = PointerType(tmp); } catch (const std::exception& error) { @@ -184,7 +172,7 @@ public: throw vtkm::cont::ErrorBadAllocation(err.str()); } - this->Capacity = PointerType(this->Begin.get() + static_cast(numberOfValues)); + this->Capacity = this->Begin + static_cast(numberOfValues); this->End = this->Capacity; return PortalType(this->Begin, this->End); @@ -206,8 +194,9 @@ public: storage->Allocate(this->GetNumberOfValues()); try { - ::thrust::copy( - this->Begin, this->End, vtkm::cont::ArrayPortalToIteratorBegin(storage->GetPortal())); + ::thrust::copy(thrust::cuda::pointer(this->Begin), + thrust::cuda::pointer(this->End), + vtkm::cont::ArrayPortalToIteratorBegin(storage->GetPortal())); } catch (...) { @@ -221,22 +210,21 @@ public: { // The operation will succeed even if this assertion fails, but this // is still supposed to be a precondition to Shrink. - VTKM_ASSERT(this->Begin.get() != nullptr && - this->Begin.get() + numberOfValues <= this->End.get()); + VTKM_ASSERT(this->Begin != nullptr && this->Begin + numberOfValues <= this->End); - this->End = PointerType(this->Begin.get() + static_cast(numberOfValues)); + this->End = this->Begin + static_cast(numberOfValues); } /// Frees all memory. /// VTKM_CONT void ReleaseResources() { - if (this->Begin.get() != nullptr) + if (this->Begin != nullptr) { - vtkm::cont::cuda::internal::CudaAllocator::Free(this->Begin.get()); - this->Begin = PointerType(static_cast(nullptr)); - this->End = PointerType(static_cast(nullptr)); - this->Capacity = PointerType(static_cast(nullptr)); + vtkm::cont::cuda::internal::CudaAllocator::Free(this->Begin); + this->Begin = nullptr; + this->End = nullptr; + this->Capacity = nullptr; } } @@ -258,7 +246,7 @@ private: this->PrepareForOutput(this->Storage->GetNumberOfValues()); ::thrust::copy(vtkm::cont::ArrayPortalToIteratorBegin(this->Storage->GetPortalConst()), vtkm::cont::ArrayPortalToIteratorEnd(this->Storage->GetPortalConst()), - this->Begin); + thrust::cuda::pointer(this->Begin)); } catch (...) { diff --git a/vtkm/cont/cuda/internal/CMakeLists.txt b/vtkm/cont/cuda/internal/CMakeLists.txt index 441477754..b6b7651ef 100644 --- a/vtkm/cont/cuda/internal/CMakeLists.txt +++ b/vtkm/cont/cuda/internal/CMakeLists.txt @@ -25,11 +25,13 @@ set(headers DeviceAdapterAlgorithmCuda.h DeviceAdapterAlgorithmThrust.h DeviceAdapterTagCuda.h + ExecutionArrayInterfaceBasicCuda.h MakeThrustIterator.h TaskTuner.h ThrustExceptionHandler.h VirtualObjectTransferCuda.h ) + vtkm_declare_headers(CUDA ${headers} TESTABLE ${VTKm_ENABLE_CUDA}) #----------------------------------------------------------------------------- @@ -39,5 +41,6 @@ endif() target_sources(vtkm_cont PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/ArrayManagerExecutionCuda.cu + ${CMAKE_CURRENT_SOURCE_DIR}/ExecutionArrayInterfaceBasicCuda.cu ${CMAKE_CURRENT_SOURCE_DIR}/CudaAllocator.cu ) diff --git a/vtkm/cont/cuda/internal/CudaAllocator.h b/vtkm/cont/cuda/internal/CudaAllocator.h index 937afda0f..aae81b4c5 100644 --- a/vtkm/cont/cuda/internal/CudaAllocator.h +++ b/vtkm/cont/cuda/internal/CudaAllocator.h @@ -42,7 +42,7 @@ struct VTKM_CONT_EXPORT CudaAllocator /// that can be accessed concurrently by the CPU and GPUs. static VTKM_CONT bool UsingManagedMemory(); - /// Returns true if the pointer is accessable from a CUDA device. + /// Returns true if the pointer is accessible from a CUDA device. static VTKM_CONT bool IsDevicePointer(const void* ptr); /// Returns true if the pointer is a CUDA pointer allocated with diff --git a/vtkm/cont/cuda/internal/DeviceAdapterAlgorithmThrust.h b/vtkm/cont/cuda/internal/DeviceAdapterAlgorithmThrust.h index 6846c4adb..6ae4da5c5 100644 --- a/vtkm/cont/cuda/internal/DeviceAdapterAlgorithmThrust.h +++ b/vtkm/cont/cuda/internal/DeviceAdapterAlgorithmThrust.h @@ -53,14 +53,13 @@ VTKM_THIRDPARTY_PRE_INCLUDE #include #include #include +#include #include #include +#include #include #include #include - -#include -#include VTKM_THIRDPARTY_POST_INCLUDE #include @@ -218,8 +217,7 @@ private: OutputPortal output, UnaryPredicate unary_predicate) { - using IteratorType = typename detail::IteratorTraits::IteratorType; - IteratorType outputBegin = IteratorBegin(output); + auto outputBegin = IteratorBegin(output); using ValueType = typename StencilPortal::ValueType; @@ -356,7 +354,7 @@ private: BinaryFunctor binary_functor, std::false_type) { - //The portal type and the initial value ARENT the same type so we have + //The portal type and the initial value AREN'T the same type so we have //to a slower approach, where we wrap the input portal inside a cast //portal using CastFunctor = vtkm::cont::internal::Cast; @@ -497,12 +495,15 @@ private: try { + ::thrust::system::cuda::vector result(1); auto end = ::thrust::inclusive_scan(ThrustCudaPolicyPerThread, IteratorBegin(input), IteratorEnd(input), IteratorBegin(output), bop); - return *(end - 1); + + ::thrust::copy_n(ThrustCudaPolicyPerThread, end - 1, 1, result.begin()); + return result[0]; } catch (...) { diff --git a/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.cu b/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.cu new file mode 100644 index 000000000..9b1897c5e --- /dev/null +++ b/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.cu @@ -0,0 +1,199 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2017 UT-Battelle, LLC. +// Copyright 2017 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#include +#include + +using vtkm::cont::cuda::internal::CudaAllocator; + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ + +ExecutionArrayInterfaceBasic::ExecutionArrayInterfaceBasic( + StorageBasicBase& storage) + : Superclass(storage) +{ +} + +DeviceAdapterId ExecutionArrayInterfaceBasic::GetDeviceId() const +{ + return VTKM_DEVICE_ADAPTER_CUDA; +} + +void ExecutionArrayInterfaceBasic::Allocate(TypelessExecutionArray& execArray, + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) const +{ + const vtkm::UInt64 numBytes = static_cast(numberOfValues) * sizeOfValue; + // Detect if we can reuse a device-accessible pointer from the control env: + if (CudaAllocator::IsDevicePointer(execArray.ArrayControl)) + { + const vtkm::UInt64 managedCapacity = + static_cast(static_cast(execArray.ArrayControlCapacity) - + static_cast(execArray.ArrayControl)); + if (managedCapacity >= numBytes) + { + if (execArray.Array && execArray.Array != execArray.ArrayControl) + { + this->Free(execArray); + } + + execArray.Array = const_cast(execArray.ArrayControl); + execArray.ArrayEnd = static_cast(execArray.Array) + numBytes; + execArray.ArrayCapacity = const_cast(execArray.ArrayControlCapacity); + return; + } + } + + if (execArray.Array != nullptr) + { + const vtkm::UInt64 cap = static_cast(static_cast(execArray.ArrayCapacity) - + static_cast(execArray.Array)); + + if (cap < numBytes) + { // Current allocation too small -- free & realloc + this->Free(execArray); + } + else + { // Reuse buffer if possible: + execArray.ArrayEnd = static_cast(execArray.Array) + numBytes; + return; + } + } + + VTKM_ASSERT(execArray.Array == nullptr); + + // Attempt to allocate: + try + { + // Cast to char* so that the pointer math below will work. + char* tmp = static_cast(CudaAllocator::Allocate(static_cast(numBytes))); + execArray.Array = tmp; + execArray.ArrayEnd = tmp + numBytes; + execArray.ArrayCapacity = tmp + numBytes; + } + catch (const std::exception& error) + { + std::ostringstream err; + err << "Failed to allocate " << numBytes << " bytes on device: " << error.what(); + throw vtkm::cont::ErrorBadAllocation(err.str()); + } +} + +void ExecutionArrayInterfaceBasic::Free( + TypelessExecutionArray& execArray) const +{ + // If we're sharing a device-accessible pointer between control/exec, don't + // actually free it -- just null the pointers here: + if (execArray.Array == execArray.ArrayControl && + CudaAllocator::IsDevicePointer(execArray.ArrayControl)) + { + execArray.Array = nullptr; + execArray.ArrayEnd = nullptr; + execArray.ArrayCapacity = nullptr; + return; + } + + if (execArray.Array != nullptr) + { + CudaAllocator::Free(execArray.Array); + execArray.Array = nullptr; + execArray.ArrayEnd = nullptr; + execArray.ArrayCapacity = nullptr; + } +} + +void ExecutionArrayInterfaceBasic::CopyFromControl( + const void* controlPtr, + void* executionPtr, + vtkm::UInt64 numBytes) const +{ + // Do nothing if we're sharing a device-accessible pointer between control and + // execution: + if (controlPtr == executionPtr && CudaAllocator::IsDevicePointer(controlPtr)) + { + CudaAllocator::PrepareForInput(executionPtr, numBytes); + return; + } + + VTKM_CUDA_CALL(cudaMemcpyAsync(executionPtr, + controlPtr, + static_cast(numBytes), + cudaMemcpyHostToDevice, + cudaStreamPerThread)); +} + +void ExecutionArrayInterfaceBasic::CopyToControl(const void* executionPtr, + void* controlPtr, + vtkm::UInt64 numBytes) const +{ + // Do nothing if we're sharing a cuda managed pointer between control and execution: + if (controlPtr == executionPtr && CudaAllocator::IsDevicePointer(controlPtr)) + { + // If we're trying to copy a shared, non-managed device pointer back to + // control throw an exception -- the pointer cannot be read from control, + // so this operation is invalid. + if (!CudaAllocator::IsManagedPointer(controlPtr)) + { + throw vtkm::cont::ErrorBadValue( + "Control pointer is a CUDA device pointer that does not supported managed access."); + } + + // If it is managed, just return and let CUDA handle the migration for us. + CudaAllocator::PrepareForControl(controlPtr, numBytes); + return; + } + + VTKM_CUDA_CALL(cudaMemcpyAsync(controlPtr, + executionPtr, + static_cast(numBytes), + cudaMemcpyDeviceToHost, + cudaStreamPerThread)); +} + +void ExecutionArrayInterfaceBasic::UsingForRead(const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const +{ + CudaAllocator::PrepareForInput(executionPtr, static_cast(numBytes)); +} + +void ExecutionArrayInterfaceBasic::UsingForWrite(const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const +{ + CudaAllocator::PrepareForOutput(executionPtr, static_cast(numBytes)); +} + +void ExecutionArrayInterfaceBasic::UsingForReadWrite( + const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const +{ + CudaAllocator::PrepareForInPlace(executionPtr, static_cast(numBytes)); +} + + +} // end namespace internal +} +} // end vtkm::cont diff --git a/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.h b/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.h new file mode 100644 index 000000000..4748e0e51 --- /dev/null +++ b/vtkm/cont/cuda/internal/ExecutionArrayInterfaceBasicCuda.h @@ -0,0 +1,64 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_cont_cuda_internal_ExecutionArrayInterfaceCuda_h +#define vtk_m_cont_cuda_internal_ExecutionArrayInterfaceCuda_h + +#include + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ +template <> +struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic + : public ExecutionArrayInterfaceBasicBase +{ + using Superclass = ExecutionArrayInterfaceBasicBase; + + VTKM_CONT ExecutionArrayInterfaceBasic(StorageBasicBase& storage); + VTKM_CONT DeviceAdapterId GetDeviceId() const final; + VTKM_CONT void Allocate(TypelessExecutionArray& execArray, + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) const final; + VTKM_CONT void Free(TypelessExecutionArray& execArray) const final; + VTKM_CONT void CopyFromControl(const void* controlPtr, + void* executionPtr, + vtkm::UInt64 numBytes) const final; + VTKM_CONT void CopyToControl(const void* executionPtr, + void* controlPtr, + vtkm::UInt64 numBytes) const final; + + VTKM_CONT void UsingForRead(const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const final; + VTKM_CONT void UsingForWrite(const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const final; + VTKM_CONT void UsingForReadWrite(const void* controlPtr, + const void* executionPtr, + vtkm::UInt64 numBytes) const final; +}; +} // namespace internal +} +} // namespace vtkm::cont + +#endif //vtk_m_cont_cuda_internal_ExecutionArrayInterfaceCuda_h diff --git a/vtkm/cont/cuda/internal/MakeThrustIterator.h b/vtkm/cont/cuda/internal/MakeThrustIterator.h index 6dd99851d..675bd7bda 100644 --- a/vtkm/cont/cuda/internal/MakeThrustIterator.h +++ b/vtkm/cont/cuda/internal/MakeThrustIterator.h @@ -20,21 +20,8 @@ #ifndef vtk_m_cont_cuda_internal_MakeThrustIterator_h #define vtk_m_cont_cuda_internal_MakeThrustIterator_h -#include -#include -#include -#include - #include -#include - -// Disable warnings we check vtkm for but Thrust does not. -VTKM_THIRDPARTY_PRE_INCLUDE -#include -#include -#include -#include -VTKM_THIRDPARTY_POST_INCLUDE +#include namespace vtkm { @@ -44,107 +31,46 @@ namespace cuda { namespace internal { -namespace detail -{ - -// Tags to specify what type of thrust iterator to use. -struct ThrustIteratorFromArrayPortalTag -{ -}; -struct ThrustIteratorDevicePtrTag -{ -}; - -// Traits to help classify what thrust iterators will be used. -template -struct ThrustIteratorTag -{ - using Type = ThrustIteratorFromArrayPortalTag; -}; -template -struct ThrustIteratorTag> -{ - using Type = ThrustIteratorDevicePtrTag; -}; -template -struct ThrustIteratorTag> -{ - using Type = ThrustIteratorDevicePtrTag; -}; - -template -struct IteratorChooser; template -struct IteratorChooser -{ - using Type = vtkm::exec::cuda::internal::IteratorFromArrayPortal; -}; -template -struct IteratorChooser -{ - using PortalToIteratorType = vtkm::cont::ArrayPortalToIterators; - - using Type = typename PortalToIteratorType::IteratorType; -}; - -template -struct IteratorTraits -{ - using PortalToIteratorType = vtkm::cont::ArrayPortalToIterators; - using Tag = typename detail::ThrustIteratorTag::Type; - using IteratorType = typename IteratorChooser::Type; -}; - -template -VTKM_CONT typename IteratorTraits::IteratorType MakeIteratorBegin( - PortalType portal, - detail::ThrustIteratorFromArrayPortalTag) -{ - return vtkm::exec::cuda::internal::IteratorFromArrayPortal(portal); -} - -template -VTKM_CONT typename IteratorTraits::IteratorType MakeIteratorBegin( - PortalType portal, - detail::ThrustIteratorDevicePtrTag) -{ - vtkm::cont::ArrayPortalToIterators iterators(portal); - return iterators.GetBegin(); -} - -template -VTKM_CONT typename IteratorTraits::IteratorType MakeIteratorEnd( - PortalType portal, - detail::ThrustIteratorFromArrayPortalTag) +inline vtkm::exec::cuda::internal::IteratorFromArrayPortal IteratorBegin( + const PortalType& portal) { vtkm::exec::cuda::internal::IteratorFromArrayPortal iterator(portal); - ::thrust::advance(iterator, static_cast(portal.GetNumberOfValues())); return iterator; } template -VTKM_CONT typename IteratorTraits::IteratorType MakeIteratorEnd( - PortalType portal, - detail::ThrustIteratorDevicePtrTag) +inline vtkm::exec::cuda::internal::IteratorFromArrayPortal IteratorEnd( + const PortalType& portal) { - vtkm::cont::ArrayPortalToIterators iterators(portal); - return iterators.GetEnd(); + vtkm::exec::cuda::internal::IteratorFromArrayPortal iterator(portal); + iterator += static_cast(portal.GetNumberOfValues()); + return iterator; } -} // namespace detail - -template -VTKM_CONT typename detail::IteratorTraits::IteratorType IteratorBegin(PortalType portal) +template +inline T* IteratorBegin(const vtkm::exec::cuda::internal::ArrayPortalFromThrust& portal) { - using IteratorTag = typename detail::IteratorTraits::Tag; - return detail::MakeIteratorBegin(portal, IteratorTag()); + return portal.GetIteratorBegin(); } -template -VTKM_CONT typename detail::IteratorTraits::IteratorType IteratorEnd(PortalType portal) +template +inline T* IteratorEnd(const vtkm::exec::cuda::internal::ArrayPortalFromThrust& portal) { - using IteratorTag = typename detail::IteratorTraits::Tag; - return detail::MakeIteratorEnd(portal, IteratorTag()); + return portal.GetIteratorEnd(); +} + +template +inline const T* IteratorBegin( + const vtkm::exec::cuda::internal::ConstArrayPortalFromThrust& portal) +{ + return portal.GetIteratorBegin(); +} + +template +inline const T* IteratorEnd(const vtkm::exec::cuda::internal::ConstArrayPortalFromThrust& portal) +{ + return portal.GetIteratorEnd(); } } } diff --git a/vtkm/cont/cuda/testing/UnitTestCudaShareUserProvidedManagedMemory.cu b/vtkm/cont/cuda/testing/UnitTestCudaShareUserProvidedManagedMemory.cu index f96f9371f..39b72e69e 100644 --- a/vtkm/cont/cuda/testing/UnitTestCudaShareUserProvidedManagedMemory.cu +++ b/vtkm/cont/cuda/testing/UnitTestCudaShareUserProvidedManagedMemory.cu @@ -78,8 +78,8 @@ void TestPrepareForInput(bool managed) vtkm::cont::ArrayHandle handle = CreateArrayHandle(32, managed); handle.PrepareForInput(vtkm::cont::DeviceAdapterTagCuda()); - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after PrepareForInput."); VTKM_TEST_ASSERT(execArray != nullptr, "No execution array after PrepareForInput."); VTKM_TEST_ASSERT(CudaAllocator::IsDevicePointer(execArray), @@ -102,8 +102,8 @@ void TestPrepareForInPlace(bool managed) vtkm::cont::ArrayHandle handle = CreateArrayHandle(32, managed); handle.PrepareForInPlace(vtkm::cont::DeviceAdapterTagCuda()); - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after PrepareForInPlace."); VTKM_TEST_ASSERT(execArray != nullptr, "No execution array after PrepareForInPlace."); VTKM_TEST_ASSERT(CudaAllocator::IsDevicePointer(execArray), @@ -127,8 +127,8 @@ void TestPrepareForOutput(bool managed) vtkm::cont::ArrayHandle handle = CreateArrayHandle(32, managed); handle.PrepareForOutput(32, vtkm::cont::DeviceAdapterTagCuda()); - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after PrepareForOutput."); VTKM_TEST_ASSERT(execArray != nullptr, "No execution array after PrepareForOutput."); VTKM_TEST_ASSERT(CudaAllocator::IsDevicePointer(execArray), @@ -151,12 +151,12 @@ void TestReleaseResourcesExecution(bool managed) vtkm::cont::ArrayHandle handle = CreateArrayHandle(32, managed); handle.PrepareForInput(vtkm::cont::DeviceAdapterTagCuda()); - ValueType* origArray = handle.Internals->ExecutionArray; + void* origArray = handle.Internals->ExecutionArray; handle.ReleaseResourcesExecution(); - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after ReleaseResourcesExecution."); VTKM_TEST_ASSERT(execArray == nullptr, @@ -178,10 +178,10 @@ void TestRoundTrip(bool managed) vtkm::cont::ArrayHandle handle = CreateArrayHandle(32, managed); handle.PrepareForOutput(32, vtkm::cont::DeviceAdapterTagCuda()); - ValueType* origContArray = handle.Internals->ControlArray.GetArray(); + void* origContArray = handle.Internals->ControlArray->GetBasePointer(); { - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after PrepareForOutput."); VTKM_TEST_ASSERT(execArray != nullptr, "No execution array after PrepareForOutput."); VTKM_TEST_ASSERT(CudaAllocator::IsDevicePointer(execArray), @@ -222,8 +222,8 @@ void TestRoundTrip(bool managed) } { - ValueType* contArray = handle.Internals->ControlArray.GetArray(); - ValueType* execArray = handle.Internals->ExecutionArray; + void* contArray = handle.Internals->ControlArray->GetBasePointer(); + void* execArray = handle.Internals->ExecutionArray; VTKM_TEST_ASSERT(contArray != nullptr, "No control array after GetPortalConst."); VTKM_TEST_ASSERT(execArray == nullptr, "Execution array not cleared after GetPortalConst."); VTKM_TEST_ASSERT(CudaAllocator::IsDevicePointer(contArray), diff --git a/vtkm/cont/internal/ArrayHandleBasicImpl.cxx b/vtkm/cont/internal/ArrayHandleBasicImpl.cxx new file mode 100644 index 000000000..106d7d54a --- /dev/null +++ b/vtkm/cont/internal/ArrayHandleBasicImpl.cxx @@ -0,0 +1,337 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2017 UT-Battelle, LLC. +// Copyright 2017 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ + +#define vtkm_cont_internal_ArrayHandleImpl_cxx + +#include + +#include +#include +#include + +#include +#ifdef VTKM_ENABLE_TBB +#include +#endif +#ifdef VTKM_ENABLE_CUDA +#include +#endif + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ + +TypelessExecutionArray::TypelessExecutionArray(const ArrayHandleImpl* data) + : Array(data->ExecutionArray) + , ArrayEnd(data->ExecutionArrayEnd) + , ArrayCapacity(data->ExecutionArrayCapacity) + , ArrayControl(data->ControlArray->GetBasePointer()) + , ArrayControlCapacity(data->ControlArray->GetCapacityPointer()) +{ +} + +ExecutionArrayInterfaceBasicBase::ExecutionArrayInterfaceBasicBase(StorageBasicBase& storage) + : ControlStorage(storage) +{ +} + +ExecutionArrayInterfaceBasicBase::~ExecutionArrayInterfaceBasicBase() +{ +} + +ArrayHandleImpl::~ArrayHandleImpl() +{ + if (this->ExecutionArrayValid && this->ExecutionInterface != nullptr && + this->ExecutionArray != nullptr) + { + TypelessExecutionArray execArray(this); + this->ExecutionInterface->Free(execArray); + } + + delete this->ControlArray; + delete this->ExecutionInterface; +} + +void ArrayHandleImpl::CheckControlArrayValid() +{ + if (!this->ControlArrayValid) + { + throw vtkm::cont::ErrorInternal( + "ArrayHandle::SyncControlArray did not make control array valid."); + } +} + +vtkm::Id ArrayHandleImpl::GetNumberOfValues(vtkm::UInt64 sizeOfT) const +{ + if (this->ControlArrayValid) + { + return this->ControlArray->GetNumberOfValues(); + } + else if (this->ExecutionArrayValid) + { + auto numBytes = + static_cast(this->ExecutionArrayEnd) - static_cast(this->ExecutionArray); + return static_cast(numBytes) / static_cast(sizeOfT); + } + else + { + return 0; + } +} + +void ArrayHandleImpl::Allocate(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfT) +{ + this->ReleaseResourcesExecutionInternal(); + this->ControlArray->AllocateValues(numberOfValues, sizeOfT); + this->ControlArrayValid = true; +} + +void ArrayHandleImpl::Shrink(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfT) +{ + VTKM_ASSERT(numberOfValues >= 0); + + if (numberOfValues > 0) + { + vtkm::Id originalNumberOfValues = this->GetNumberOfValues(sizeOfT); + + if (numberOfValues < originalNumberOfValues) + { + if (this->ControlArrayValid) + { + this->ControlArray->Shrink(numberOfValues); + } + if (this->ExecutionArrayValid) + { + auto offset = static_cast(numberOfValues) * sizeOfT; + this->ExecutionArrayEnd = static_cast(this->ExecutionArray) + offset; + } + } + else if (numberOfValues == originalNumberOfValues) + { + // Nothing to do. + } + else // numberOfValues > originalNumberOfValues + { + throw vtkm::cont::ErrorBadValue("ArrayHandle::Shrink cannot be used to grow array."); + } + + VTKM_ASSERT(this->GetNumberOfValues(sizeOfT) == numberOfValues); + } + else // numberOfValues == 0 + { + // If we are shrinking to 0, there is nothing to save and we might as well + // free up memory. Plus, some storage classes expect that data will be + // deallocated when the size goes to zero. + this->Allocate(0, sizeOfT); + } +} + +void ArrayHandleImpl::ReleaseResources() +{ + this->ReleaseResourcesExecutionInternal(); + + if (this->ControlArrayValid) + { + this->ControlArray->ReleaseResources(); + this->ControlArrayValid = false; + } +} + +void ArrayHandleImpl::PrepareForInput(vtkm::UInt64 sizeOfT) const +{ + const vtkm::Id numVals = this->GetNumberOfValues(sizeOfT); + const vtkm::UInt64 numBytes = sizeOfT * static_cast(numVals); + if (!this->ExecutionArrayValid) + { + // Initialize an empty array if needed: + if (!this->ControlArrayValid) + { + this->ControlArray->AllocateValues(0, sizeOfT); + this->ControlArrayValid = true; + } + + TypelessExecutionArray execArray(this); + + this->ExecutionInterface->Allocate(execArray, numVals, sizeOfT); + + this->ExecutionInterface->CopyFromControl( + this->ControlArray->GetBasePointer(), this->ExecutionArray, numBytes); + + this->ExecutionArrayValid = true; + } + this->ExecutionInterface->UsingForRead( + this->ControlArray->GetBasePointer(), this->ExecutionArray, numBytes); +} + +void ArrayHandleImpl::PrepareForOutput(vtkm::Id numVals, vtkm::UInt64 sizeOfT) +{ + // Invalidate control arrays since we expect the execution data to be + // overwritten. Don't free control resources in case they're shared with + // the execution environment. + this->ControlArrayValid = false; + + TypelessExecutionArray execArray(this); + + this->ExecutionInterface->Allocate(execArray, numVals, sizeOfT); + const vtkm::UInt64 numBytes = sizeOfT * static_cast(numVals); + this->ExecutionInterface->UsingForWrite( + this->ControlArray->GetBasePointer(), this->ExecutionArray, numBytes); + + this->ExecutionArrayValid = true; +} + +void ArrayHandleImpl::PrepareForInPlace(vtkm::UInt64 sizeOfT) +{ + const vtkm::Id numVals = this->GetNumberOfValues(sizeOfT); + const vtkm::UInt64 numBytes = sizeOfT * static_cast(numVals); + + if (!this->ExecutionArrayValid) + { + // Initialize an empty array if needed: + if (!this->ControlArrayValid) + { + this->ControlArray->AllocateValues(0, sizeOfT); + this->ControlArrayValid = true; + } + + TypelessExecutionArray execArray(this); + + this->ExecutionInterface->Allocate(execArray, numVals, sizeOfT); + + this->ExecutionInterface->CopyFromControl( + this->ControlArray->GetBasePointer(), this->ExecutionArray, numBytes); + + this->ExecutionArrayValid = true; + } + + this->ExecutionInterface->UsingForReadWrite( + this->ControlArray->GetBasePointer(), this->ExecutionArray, numBytes); + + // Invalidate the control array, since we expect the values to be modified: + this->ControlArrayValid = false; +} + +bool ArrayHandleImpl::PrepareForDevice(DeviceAdapterId devId, vtkm::UInt64 sizeOfT) const +{ + // Check if the current device matches the last one and sync through + // the control environment if the device changes. + if (this->ExecutionInterface) + { + if (this->ExecutionInterface->GetDeviceId() == devId) + { + // All set, nothing to do. + return false; + } + else + { + // Update the device allocator: + this->SyncControlArray(sizeOfT); + TypelessExecutionArray execArray(this); + this->ExecutionInterface->Free(execArray); + delete this->ExecutionInterface; + this->ExecutionInterface = nullptr; + this->ExecutionArrayValid = false; + } + } + + VTKM_ASSERT(this->ExecutionInterface == nullptr); + VTKM_ASSERT(!this->ExecutionArrayValid); + switch (devId) + { +#ifdef VTKM_ENABLE_TBB + case VTKM_DEVICE_ADAPTER_TBB: + this->ExecutionInterface = + new ExecutionArrayInterfaceBasic(*this->ControlArray); + break; +#endif + +//this doesn't need to be guarded as a .cu file as it is calling host methods +//and not cuda code directly +#ifdef VTKM_ENABLE_CUDA + case VTKM_DEVICE_ADAPTER_CUDA: + + this->ExecutionInterface = + new ExecutionArrayInterfaceBasic(*this->ControlArray); + break; +#endif + default: + this->ExecutionInterface = + new ExecutionArrayInterfaceBasic(*this->ControlArray); + break; + } + return true; +} + +DeviceAdapterId ArrayHandleImpl::GetDeviceAdapterId() const +{ + return this->ExecutionArrayValid ? this->ExecutionInterface->GetDeviceId() + : VTKM_DEVICE_ADAPTER_UNDEFINED; +} + + +void ArrayHandleImpl::SyncControlArray(vtkm::UInt64 sizeOfT) const +{ + if (!this->ControlArrayValid) + { + // Need to change some state that does not change the logical state from + // an external point of view. + if (this->ExecutionArrayValid) + { + const vtkm::UInt64 numBytes = static_cast( + static_cast(this->ExecutionArrayEnd) - static_cast(this->ExecutionArray)); + const vtkm::Id numVals = static_cast(numBytes / sizeOfT); + + this->ControlArray->AllocateValues(numVals, sizeOfT); + this->ExecutionInterface->CopyToControl( + this->ExecutionArray, this->ControlArray->GetBasePointer(), numBytes); + this->ControlArrayValid = true; + } + else + { + // This array is in the null state (there is nothing allocated), but + // the calling function wants to do something with the array. Put this + // class into a valid state by allocating an array of size 0. + this->ControlArray->AllocateValues(0, sizeOfT); + this->ControlArrayValid = true; + } + } +} + +void ArrayHandleImpl::ReleaseResourcesExecutionInternal() +{ + if (this->ExecutionArrayValid) + { + TypelessExecutionArray execArray(this); + this->ExecutionInterface->Free(execArray); + this->ExecutionArrayValid = false; + } +} + +} // end namespace internal +} +} // end vtkm::cont + +#ifdef VTKM_MSVC +//Export this when being used with std::shared_ptr +template class VTKM_CONT_EXPORT std::shared_ptr; +#endif diff --git a/vtkm/cont/internal/ArrayHandleBasicImpl.h b/vtkm/cont/internal/ArrayHandleBasicImpl.h index 465bfb222..e6fe27316 100644 --- a/vtkm/cont/internal/ArrayHandleBasicImpl.h +++ b/vtkm/cont/internal/ArrayHandleBasicImpl.h @@ -35,22 +35,13 @@ namespace cont namespace internal { +struct ArrayHandleImpl; + /// Type-agnostic container for an execution memory buffer. -struct VTKM_ALWAYS_EXPORT TypelessExecutionArray +struct VTKM_CONT_EXPORT TypelessExecutionArray { - VTKM_CONT - TypelessExecutionArray(void*& array, - void*& arrayEnd, - void*& arrayCapacity, - const void* arrayControl, - const void* arrayControlCapacity) - : Array(array) - , ArrayEnd(arrayEnd) - , ArrayCapacity(arrayCapacity) - , ArrayControl(arrayControl) - , ArrayControlCapacity(arrayControlCapacity) - { - } + + TypelessExecutionArray(const ArrayHandleImpl* data); void*& Array; void*& ArrayEnd; @@ -94,7 +85,9 @@ struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasicBase /// If (capacity - base) < @a numBytes, the buffer will be freed and /// reallocated. If (capacity - base) >= numBytes, a new end is marked. VTKM_CONT - virtual void Allocate(TypelessExecutionArray& execArray, vtkm::UInt64 numBytes) const = 0; + virtual void Allocate(TypelessExecutionArray& execArray, + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) const = 0; /// Release the buffer held by @a execArray and reset all pointer to null. VTKM_CONT @@ -134,13 +127,81 @@ protected: template struct ExecutionArrayInterfaceBasic; +struct VTKM_CONT_EXPORT ArrayHandleImpl +{ + VTKM_CONT + template + explicit ArrayHandleImpl(T) + : ControlArrayValid(false) + , ControlArray(new vtkm::cont::internal::Storage()) + , ExecutionInterface(nullptr) + , ExecutionArrayValid(false) + , ExecutionArray(nullptr) + , ExecutionArrayEnd(nullptr) + , ExecutionArrayCapacity(nullptr) + { + } + + VTKM_CONT + template + explicit ArrayHandleImpl( + const vtkm::cont::internal::Storage& storage) + : ControlArrayValid(true) + , ControlArray(new vtkm::cont::internal::Storage(storage)) + , ExecutionInterface(nullptr) + , ExecutionArrayValid(false) + , ExecutionArray(nullptr) + , ExecutionArrayEnd(nullptr) + , ExecutionArrayCapacity(nullptr) + { + } + + VTKM_CONT ~ArrayHandleImpl(); + + VTKM_CONT ArrayHandleImpl(const ArrayHandleImpl&) = delete; + VTKM_CONT void operator=(const ArrayHandleImpl&) = delete; + + //Throws ErrorInternal if ControlArrayValid == false + VTKM_CONT void CheckControlArrayValid() noexcept(false); + + VTKM_CONT vtkm::Id GetNumberOfValues(vtkm::UInt64 sizeOfT) const; + VTKM_CONT void Allocate(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfT); + VTKM_CONT void Shrink(vtkm::Id numberOfValues, vtkm::UInt64 sizeOfT); + + VTKM_CONT void SyncControlArray(vtkm::UInt64 sizeofT) const; + VTKM_CONT void ReleaseResources(); + VTKM_CONT void ReleaseResourcesExecutionInternal(); + + VTKM_CONT void PrepareForInput(vtkm::UInt64 sizeofT) const; + VTKM_CONT void PrepareForOutput(vtkm::Id numVals, vtkm::UInt64 sizeofT); + VTKM_CONT void PrepareForInPlace(vtkm::UInt64 sizeofT); + + // Check if the current device matches the last one. If they don't match + // this moves all data back from execution environment and deletes the + // ExecutionInterface instance. + // Returns true when the caller needs to reallocate ExecutionInterface + VTKM_CONT bool PrepareForDevice(DeviceAdapterId devId, vtkm::UInt64 sizeofT) const; + + VTKM_CONT DeviceAdapterId GetDeviceAdapterId() const; + + mutable bool ControlArrayValid; + StorageBasicBase* ControlArray; + + mutable ExecutionArrayInterfaceBasicBase* ExecutionInterface; + mutable bool ExecutionArrayValid; + mutable void* ExecutionArray; + mutable void* ExecutionArrayEnd; + mutable void* ExecutionArrayCapacity; +}; + } // end namespace internal /// Specialization of ArrayHandle for Basic storage. The goal here is to reduce /// the amount of codegen for the common case of Basic storage when we build /// the common arrays into libvtkm_cont. template -class ArrayHandle : public ::vtkm::cont::internal::ArrayHandleBase +class VTKM_ALWAYS_EXPORT ArrayHandle + : public ::vtkm::cont::internal::ArrayHandleBase { private: using Thisclass = ArrayHandle; @@ -154,7 +215,6 @@ public: using ValueType = T; using PortalControl = typename StorageType::PortalType; using PortalConstControl = typename StorageType::PortalConstType; - struct InternalStruct; template struct ExecutionTypes @@ -167,7 +227,6 @@ public: VTKM_CONT ArrayHandle(const Thisclass& src); VTKM_CONT ArrayHandle(const Thisclass&& src); VTKM_CONT ArrayHandle(const StorageType& storage); - VTKM_CONT ArrayHandle(const std::shared_ptr& i); VTKM_CONT ~ArrayHandle(); @@ -214,65 +273,19 @@ public: VTKM_CONT void SyncControlArray() const; VTKM_CONT void ReleaseResourcesExecutionInternal(); - struct VTKM_ALWAYS_EXPORT InternalStruct - { - InternalStruct() - : ControlArrayValid(false) - , ExecutionInterface(nullptr) - , ExecutionArrayValid(false) - , ExecutionArray(nullptr) - , ExecutionArrayEnd(nullptr) - , ExecutionArrayCapacity(nullptr) - { - } - - InternalStruct(const StorageType& storage) - : ControlArrayValid(true) - , ControlArray(storage) - , ExecutionInterface(nullptr) - , ExecutionArrayValid(false) - , ExecutionArray(nullptr) - , ExecutionArrayEnd(nullptr) - , ExecutionArrayCapacity(nullptr) - { - } - - ~InternalStruct() - { - if (this->ExecutionArrayValid && this->ExecutionInterface != nullptr && - this->ExecutionArray != nullptr) - { - internal::TypelessExecutionArray execArray( - reinterpret_cast(this->ExecutionArray), - reinterpret_cast(this->ExecutionArrayEnd), - reinterpret_cast(this->ExecutionArrayCapacity), - this->ControlArray.GetBasePointer(), - this->ControlArray.GetCapacityPointer()); - this->ExecutionInterface->Free(execArray); - } - - delete this->ExecutionInterface; - } - - InternalStruct(const InternalStruct&) = delete; - void operator=(const InternalStruct&) = delete; - - bool ControlArrayValid; - StorageType ControlArray; - - internal::ExecutionArrayInterfaceBasicBase* ExecutionInterface; - bool ExecutionArrayValid; - ValueType* ExecutionArray; - ValueType* ExecutionArrayEnd; - ValueType* ExecutionArrayCapacity; - }; - - std::shared_ptr Internals; + std::shared_ptr Internals; }; } // end namespace cont } // end namespace vtkm +#ifndef vtkm_cont_internal_ArrayHandleImpl_cxx +#ifdef VTKM_MSVC +extern template class VTKM_CONT_TEMPLATE_EXPORT + std::shared_ptr; +#endif +#endif + #include #endif // vtk_m_cont_internal_ArrayHandleBasicImpl_h diff --git a/vtkm/cont/internal/ArrayHandleBasicImpl.hxx b/vtkm/cont/internal/ArrayHandleBasicImpl.hxx index be03fe2a4..fea10127b 100644 --- a/vtkm/cont/internal/ArrayHandleBasicImpl.hxx +++ b/vtkm/cont/internal/ArrayHandleBasicImpl.hxx @@ -27,10 +27,9 @@ namespace vtkm { namespace cont { - template ArrayHandle::ArrayHandle() - : Internals(new InternalStruct) + : Internals(new internal::ArrayHandleImpl(T{})) { } @@ -48,13 +47,7 @@ ArrayHandle::ArrayHandle(const Thisclass&& src) template ArrayHandle::ArrayHandle(const StorageType& storage) - : Internals(new InternalStruct(storage)) -{ -} - -template -ArrayHandle::ArrayHandle(const std::shared_ptr& i) - : Internals(i) + : Internals(new internal::ArrayHandleImpl(storage)) { } @@ -107,15 +100,11 @@ template typename ArrayHandle::StorageType& ArrayHandle::GetStorage() { this->SyncControlArray(); - if (this->Internals->ControlArrayValid) - { - return this->Internals->ControlArray; - } - else - { - throw vtkm::cont::ErrorInternal( - "ArrayHandle::SyncControlArray did not make control array valid."); - } + this->Internals->CheckControlArrayValid(); + //CheckControlArrayValid will throw an exception if this->Internals->ControlArrayValid + //is not valid + + return *(static_cast(this->Internals->ControlArray)); } template @@ -123,15 +112,11 @@ const typename ArrayHandle::StorageType& ArrayHandle::GetStorage() const { this->SyncControlArray(); - if (this->Internals->ControlArrayValid) - { - return this->Internals->ControlArray; - } - else - { - throw vtkm::cont::ErrorInternal( - "ArrayHandle::SyncControlArray did not make control array valid."); - } + this->Internals->CheckControlArrayValid(); + //CheckControlArrayValid will throw an exception if this->Internals->ControlArrayValid + //is not valid + + return *(static_cast(this->Internals->ControlArray)); } template @@ -139,19 +124,17 @@ typename ArrayHandle::PortalControl ArrayHandle::GetPortalControl() { this->SyncControlArray(); - if (this->Internals->ControlArrayValid) - { - // If the user writes into the iterator we return, then the execution - // array will become invalid. Play it safe and release the execution - // resources. (Use the const version to preserve the execution array.) - this->ReleaseResourcesExecutionInternal(); - return this->Internals->ControlArray.GetPortal(); - } - else - { - throw vtkm::cont::ErrorInternal( - "ArrayHandle::SyncControlArray did not make control array valid."); - } + this->Internals->CheckControlArrayValid(); + //CheckControlArrayValid will throw an exception if this->Internals->ControlArrayValid + //is not valid + + + // If the user writes into the iterator we return, then the execution + // array will become invalid. Play it safe and release the execution + // resources. (Use the const version to preserve the execution array.) + this->ReleaseResourcesExecutionInternal(); + StorageType* privStorage = static_cast(this->Internals->ControlArray); + return privStorage->GetPortal(); } @@ -160,81 +143,30 @@ typename ArrayHandle::PortalConstControl ArrayHandle::GetPortalConstControl() const { this->SyncControlArray(); - if (this->Internals->ControlArrayValid) - { - return this->Internals->ControlArray.GetPortalConst(); - } - else - { - throw vtkm::cont::ErrorInternal( - "ArrayHandle::SyncControlArray did not make control array valid."); - } + this->Internals->CheckControlArrayValid(); + //CheckControlArrayValid will throw an exception if this->Internals->ControlArrayValid + //is not valid + + StorageType* privStorage = static_cast(this->Internals->ControlArray); + return privStorage->GetPortalConst(); } template vtkm::Id ArrayHandle::GetNumberOfValues() const { - if (this->Internals->ControlArrayValid) - { - return this->Internals->ControlArray.GetNumberOfValues(); - } - else if (this->Internals->ExecutionArrayValid) - { - return static_cast(this->Internals->ExecutionArrayEnd - - this->Internals->ExecutionArray); - } - else - { - return 0; - } + return this->Internals->GetNumberOfValues(sizeof(T)); } template void ArrayHandle::Allocate(vtkm::Id numberOfValues) { - this->ReleaseResourcesExecutionInternal(); - this->Internals->ControlArray.Allocate(numberOfValues); - this->Internals->ControlArrayValid = true; + this->Internals->Allocate(numberOfValues, sizeof(T)); } template void ArrayHandle::Shrink(vtkm::Id numberOfValues) { - VTKM_ASSERT(numberOfValues >= 0); - - if (numberOfValues > 0) - { - vtkm::Id originalNumberOfValues = this->GetNumberOfValues(); - - if (numberOfValues < originalNumberOfValues) - { - if (this->Internals->ControlArrayValid) - { - this->Internals->ControlArray.Shrink(numberOfValues); - } - if (this->Internals->ExecutionArrayValid) - { - this->Internals->ExecutionArrayEnd = this->Internals->ExecutionArray + numberOfValues; - } - } - else if (numberOfValues == originalNumberOfValues) - { - // Nothing to do. - } - else // numberOfValues > originalNumberOfValues - { - throw vtkm::cont::ErrorBadValue("ArrayHandle::Shrink cannot be used to grow array."); - } - - VTKM_ASSERT(this->GetNumberOfValues() == numberOfValues); - } - else // numberOfValues == 0 - { - // If we are shrinking to 0, there is nothing to save and we might as well - // free up memory. Plus, some storage classes expect that data will be - // deallocated when the size goes to zero. - this->Allocate(0); - } + this->Internals->Shrink(numberOfValues, sizeof(T)); } template @@ -243,19 +175,13 @@ void ArrayHandle::ReleaseResourcesExecution() // Save any data in the execution environment by making sure it is synced // with the control environment. this->SyncControlArray(); - this->ReleaseResourcesExecutionInternal(); + this->Internals->ReleaseResourcesExecutionInternal(); } template void ArrayHandle::ReleaseResources() { - this->ReleaseResourcesExecutionInternal(); - - if (this->Internals->ControlArrayValid) - { - this->Internals->ControlArray.ReleaseResources(); - this->Internals->ControlArrayValid = false; - } + this->Internals->ReleaseResources(); } template @@ -264,41 +190,12 @@ typename ArrayHandle::template ExecutionTypes::PrepareForInput(DeviceAdapterTag device) const { VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); - InternalStruct* priv = const_cast(this->Internals.get()); - this->PrepareForDevice(device); - const vtkm::UInt64 numBytes = static_cast(sizeof(ValueType)) * - static_cast(this->GetStorage().GetNumberOfValues()); - - if (!this->Internals->ExecutionArrayValid) - { - // Initialize an empty array if needed: - if (!this->Internals->ControlArrayValid) - { - this->Internals->ControlArray.Allocate(0); - this->Internals->ControlArrayValid = true; - } - - internal::TypelessExecutionArray execArray( - reinterpret_cast(priv->ExecutionArray), - reinterpret_cast(priv->ExecutionArrayEnd), - reinterpret_cast(priv->ExecutionArrayCapacity), - this->Internals->ControlArray.GetBasePointer(), - this->Internals->ControlArray.GetCapacityPointer()); - - priv->ExecutionInterface->Allocate(execArray, numBytes); - - priv->ExecutionInterface->CopyFromControl( - priv->ControlArray.GetArray(), priv->ExecutionArray, numBytes); - - this->Internals->ExecutionArrayValid = true; - } - this->Internals->ExecutionInterface->UsingForRead( - priv->ControlArray.GetArray(), priv->ExecutionArray, numBytes); - - return PortalFactory::CreatePortalConst(this->Internals->ExecutionArray, - this->Internals->ExecutionArrayEnd); + this->Internals->PrepareForInput(sizeof(T)); + return PortalFactory::CreatePortalConst( + static_cast(this->Internals->ExecutionArray), + static_cast(this->Internals->ExecutionArrayEnd)); } template @@ -307,34 +204,12 @@ typename ArrayHandle::template ExecutionTypes::PrepareForOutput(vtkm::Id numVals, DeviceAdapterTag device) { VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); - InternalStruct* priv = const_cast(this->Internals.get()); - this->PrepareForDevice(device); - // Invalidate control arrays since we expect the execution data to be - // overwritten. Don't free control resources in case they're shared with - // the execution environment. - this->Internals->ControlArrayValid = false; - - internal::TypelessExecutionArray execArray(reinterpret_cast(priv->ExecutionArray), - reinterpret_cast(priv->ExecutionArrayEnd), - reinterpret_cast(priv->ExecutionArrayCapacity), - this->Internals->ControlArray.GetBasePointer(), - this->Internals->ControlArray.GetCapacityPointer()); - - const vtkm::UInt64 numBytes = - static_cast(sizeof(ValueType)) * static_cast(numVals); - - this->Internals->ExecutionInterface->Allocate(execArray, numBytes); - - this->Internals->ExecutionInterface->UsingForWrite( - priv->ControlArray.GetArray(), priv->ExecutionArray, numBytes); - - this->Internals->ExecutionArrayValid = true; - - - return PortalFactory::CreatePortal(this->Internals->ExecutionArray, - this->Internals->ExecutionArrayEnd); + this->Internals->PrepareForOutput(numVals, sizeof(T)); + return PortalFactory::CreatePortal( + static_cast(this->Internals->ExecutionArray), + static_cast(this->Internals->ExecutionArrayEnd)); } template @@ -343,45 +218,12 @@ typename ArrayHandle::template ExecutionTypes::PrepareForInPlace(DeviceAdapterTag device) { VTKM_IS_DEVICE_ADAPTER_TAG(DeviceAdapterTag); - InternalStruct* priv = const_cast(this->Internals.get()); - this->PrepareForDevice(device); - const vtkm::UInt64 numBytes = static_cast(sizeof(ValueType)) * - static_cast(this->GetStorage().GetNumberOfValues()); - - if (!this->Internals->ExecutionArrayValid) - { - // Initialize an empty array if needed: - if (!this->Internals->ControlArrayValid) - { - this->Internals->ControlArray.Allocate(0); - this->Internals->ControlArrayValid = true; - } - - internal::TypelessExecutionArray execArray( - reinterpret_cast(this->Internals->ExecutionArray), - reinterpret_cast(this->Internals->ExecutionArrayEnd), - reinterpret_cast(this->Internals->ExecutionArrayCapacity), - this->Internals->ControlArray.GetBasePointer(), - this->Internals->ControlArray.GetCapacityPointer()); - - priv->ExecutionInterface->Allocate(execArray, numBytes); - - priv->ExecutionInterface->CopyFromControl( - priv->ControlArray.GetArray(), priv->ExecutionArray, numBytes); - - this->Internals->ExecutionArrayValid = true; - } - - priv->ExecutionInterface->UsingForReadWrite( - priv->ControlArray.GetArray(), priv->ExecutionArray, numBytes); - - // Invalidate the control array, since we expect the values to be modified: - this->Internals->ControlArrayValid = false; - - return PortalFactory::CreatePortal(this->Internals->ExecutionArray, - this->Internals->ExecutionArrayEnd); + this->Internals->PrepareForInPlace(sizeof(T)); + return PortalFactory::CreatePortal( + static_cast(this->Internals->ExecutionArray), + static_cast(this->Internals->ExecutionArrayEnd)); } template @@ -389,92 +231,25 @@ template void ArrayHandle::PrepareForDevice(DeviceAdapterTag) const { DeviceAdapterId devId = DeviceAdapterTraits::GetId(); - InternalStruct* priv = const_cast(this->Internals.get()); - - // Check if the current device matches the last one and sync through - // the control environment if the device changes. - if (this->Internals->ExecutionInterface) - { - if (this->Internals->ExecutionInterface->GetDeviceId() == devId) - { - // All set, nothing to do. - return; - } - else - { - // Update the device allocator: - this->SyncControlArray(); - internal::TypelessExecutionArray execArray( - reinterpret_cast(priv->ExecutionArray), - reinterpret_cast(priv->ExecutionArrayEnd), - reinterpret_cast(priv->ExecutionArrayCapacity), - this->Internals->ControlArray.GetBasePointer(), - this->Internals->ControlArray.GetCapacityPointer()); - priv->ExecutionInterface->Free(execArray); - delete priv->ExecutionInterface; - priv->ExecutionInterface = nullptr; - priv->ExecutionArrayValid = false; - } - } - - VTKM_ASSERT(priv->ExecutionInterface == nullptr); - VTKM_ASSERT(!priv->ExecutionArrayValid); - - priv->ExecutionInterface = - new internal::ExecutionArrayInterfaceBasic(this->Internals->ControlArray); + this->Internals->PrepareForDevice(devId, sizeof(T)); } template DeviceAdapterId ArrayHandle::GetDeviceAdapterId() const { - return this->Internals->ExecutionArrayValid ? this->Internals->ExecutionInterface->GetDeviceId() - : VTKM_DEVICE_ADAPTER_UNDEFINED; + return this->Internals->GetDeviceAdapterId(); } template void ArrayHandle::SyncControlArray() const { - if (!this->Internals->ControlArrayValid) - { - // Need to change some state that does not change the logical state from - // an external point of view. - InternalStruct* priv = const_cast(this->Internals.get()); - if (this->Internals->ExecutionArrayValid) - { - const vtkm::Id numValues = - static_cast(this->Internals->ExecutionArrayEnd - this->Internals->ExecutionArray); - const vtkm::UInt64 numBytes = - static_cast(sizeof(ValueType)) * static_cast(numValues); - priv->ControlArray.Allocate(numValues); - priv->ExecutionInterface->CopyToControl( - priv->ExecutionArray, priv->ControlArray.GetArray(), numBytes); - priv->ControlArrayValid = true; - } - else - { - // This array is in the null state (there is nothing allocated), but - // the calling function wants to do something with the array. Put this - // class into a valid state by allocating an array of size 0. - priv->ControlArray.Allocate(0); - priv->ControlArrayValid = true; - } - } + this->Internals->SyncControlArray(sizeof(T)); } template void ArrayHandle::ReleaseResourcesExecutionInternal() { - if (this->Internals->ExecutionArrayValid) - { - internal::TypelessExecutionArray execArray( - reinterpret_cast(this->Internals->ExecutionArray), - reinterpret_cast(this->Internals->ExecutionArrayEnd), - reinterpret_cast(this->Internals->ExecutionArrayCapacity), - this->Internals->ControlArray.GetBasePointer(), - this->Internals->ControlArray.GetCapacityPointer()); - this->Internals->ExecutionInterface->Free(execArray); - this->Internals->ExecutionArrayValid = false; - } + this->Internals->ReleaseResourcesExecutionInternal(); } } } // end namespace vtkm::cont diff --git a/vtkm/cont/internal/ArrayManagerExecution.h b/vtkm/cont/internal/ArrayManagerExecution.h index 4adc9e1a9..0eb9e0f0d 100644 --- a/vtkm/cont/internal/ArrayManagerExecution.h +++ b/vtkm/cont/internal/ArrayManagerExecution.h @@ -40,7 +40,7 @@ namespace internal /// any resources in its destructor. /// /// This class typically takes on one of two forms. If the control and -/// execution environments have seperate memory spaces, then this class +/// execution environments have separate memory spaces, then this class /// behaves how you would expect. It allocates/deallocates arrays and copies /// data. However, if the control and execution environments share the same /// memory space, this class should delegate all its operations to the diff --git a/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.cxx b/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.cxx index d9347dfdd..8dc0571d9 100644 --- a/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.cxx +++ b/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.cxx @@ -34,12 +34,12 @@ ExecutionArrayInterfaceBasicShareWithControl::ExecutionArrayInterfaceBasicShareW } void ExecutionArrayInterfaceBasicShareWithControl::Allocate(TypelessExecutionArray& execArray, - vtkm::UInt64 numBytes) const + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) const { - this->ControlStorage.AllocateBytes(numBytes); - + this->ControlStorage.AllocateValues(numberOfValues, sizeOfValue); execArray.Array = this->ControlStorage.GetBasePointer(); - execArray.ArrayEnd = this->ControlStorage.GetEndPointer(); + execArray.ArrayEnd = this->ControlStorage.GetEndPointer(numberOfValues, sizeOfValue); execArray.ArrayCapacity = this->ControlStorage.GetCapacityPointer(); } diff --git a/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.h b/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.h index 0589c1481..ab99460c7 100644 --- a/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.h +++ b/vtkm/cont/internal/ArrayManagerExecutionShareWithControl.h @@ -139,7 +139,9 @@ struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasicShareWithControl VTKM_CONT ExecutionArrayInterfaceBasicShareWithControl(StorageBasicBase& storage); - VTKM_CONT void Allocate(TypelessExecutionArray& execArray, vtkm::UInt64 numBytes) const final; + VTKM_CONT void Allocate(TypelessExecutionArray& execArray, + vtkm::Id numberOfValues, + vtkm::UInt64 sizeOfValue) const final; VTKM_CONT void Free(TypelessExecutionArray& execArray) const final; VTKM_CONT void CopyFromControl(const void* src, void* dst, vtkm::UInt64 bytes) const final; diff --git a/vtkm/cont/internal/DeviceAdapterAlgorithmGeneral.h b/vtkm/cont/internal/DeviceAdapterAlgorithmGeneral.h index baa61e183..502d4b8f2 100644 --- a/vtkm/cont/internal/DeviceAdapterAlgorithmGeneral.h +++ b/vtkm/cont/internal/DeviceAdapterAlgorithmGeneral.h @@ -763,6 +763,37 @@ public: DerivedAlgorithm::Sort(zipHandle, internal::KeyCompare(binary_compare)); } + template + VTKM_CONT static void Transform(const vtkm::cont::ArrayHandle& input1, + const vtkm::cont::ArrayHandle& input2, + vtkm::cont::ArrayHandle& output, + BinaryFunctor binaryFunctor) + { + vtkm::Id numValues = vtkm::Min(input1.GetNumberOfValues(), input2.GetNumberOfValues()); + if (numValues <= 0) + { + return; + } + + auto input1Portal = input1.PrepareForInput(DeviceAdapterTag()); + auto input2Portal = input2.PrepareForInput(DeviceAdapterTag()); + auto outputPortal = output.PrepareForOutput(numValues, DeviceAdapterTag()); + + BinaryTransformKernel + binaryKernel(input1Portal, input2Portal, outputPortal, binaryFunctor); + DerivedAlgorithm::Schedule(binaryKernel, numValues); + } + + //}; //-------------------------------------------------------------------------- // Unique template @@ -966,7 +997,7 @@ private: /// \brief Class providing a device-specific support for selecting the optimal /// Task type for a given worklet. /// -/// When worklets are launched inside the execution enviornment we need to +/// When worklets are launched inside the execution environment we need to /// ask the device adapter what is the preferred execution style, be it /// a tiled iteration pattern, or strided. This class /// diff --git a/vtkm/cont/internal/FunctorsGeneral.h b/vtkm/cont/internal/FunctorsGeneral.h index 008e0db9c..aedc709e5 100644 --- a/vtkm/cont/internal/FunctorsGeneral.h +++ b/vtkm/cont/internal/FunctorsGeneral.h @@ -881,6 +881,38 @@ struct ScanKernel : vtkm::exec::FunctorBase } } }; + +template +struct BinaryTransformKernel : vtkm::exec::FunctorBase +{ + InPortalType1 InPortal1; + InPortalType2 InPortal2; + OutPortalType OutPortal; + BinaryFunctor BinaryOperator; + + VTKM_CONT + BinaryTransformKernel(const InPortalType1& inPortal1, + const InPortalType2& inPortal2, + const OutPortalType& outPortal, + BinaryFunctor binaryOperator) + : InPortal1(inPortal1) + , InPortal2(inPortal2) + , OutPortal(outPortal) + , BinaryOperator(binaryOperator) + { + } + + VTKM_SUPPRESS_EXEC_WARNINGS + VTKM_EXEC + void operator()(vtkm::Id index) const + { + this->OutPortal.Set( + index, this->BinaryOperator(this->InPortal1.Get(index), this->InPortal2.Get(index))); + } +}; } } } // namespace vtkm::cont::internal diff --git a/vtkm/cont/internal/testing/UnitTestArrayPortalFromIterators.cxx b/vtkm/cont/internal/testing/UnitTestArrayPortalFromIterators.cxx index 60ffbca3b..89a29e5ad 100644 --- a/vtkm/cont/internal/testing/UnitTestArrayPortalFromIterators.cxx +++ b/vtkm/cont/internal/testing/UnitTestArrayPortalFromIterators.cxx @@ -119,7 +119,7 @@ struct TemplatedTests VTKM_TEST_ASSERT(const_portal.GetNumberOfValues() == ARRAY_SIZE, "Const portal array size wrong."); - std::cout << " Check inital value." << std::endl; + std::cout << " Check initial value." << std::endl; VTKM_TEST_ASSERT(CheckPortal(portal, ORIGINAL_VALUE), "Portal iterator has bad value."); VTKM_TEST_ASSERT(CheckPortal(const_portal, ORIGINAL_VALUE), "Const portal iterator has bad value."); diff --git a/vtkm/cont/serial/internal/ArrayManagerExecutionSerial.h b/vtkm/cont/serial/internal/ArrayManagerExecutionSerial.h index ca12620af..886a8c44f 100644 --- a/vtkm/cont/serial/internal/ArrayManagerExecutionSerial.h +++ b/vtkm/cont/serial/internal/ArrayManagerExecutionSerial.h @@ -24,6 +24,7 @@ #include #include #include +#include namespace vtkm { @@ -62,19 +63,6 @@ struct ExecutionPortalFactoryBasic using Superclass::CreatePortalConst; }; -template <> -struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic - : public ExecutionArrayInterfaceBasicShareWithControl -{ - using Superclass = ExecutionArrayInterfaceBasicShareWithControl; - - VTKM_CONT - ExecutionArrayInterfaceBasic(StorageBasicBase& storage); - - VTKM_CONT - virtual DeviceAdapterId GetDeviceId() const final { return VTKM_DEVICE_ADAPTER_SERIAL; } -}; - } // namespace internal #ifndef vtk_m_cont_serial_internal_ArrayManagerExecutionSerial_cxx diff --git a/vtkm/cont/serial/internal/CMakeLists.txt b/vtkm/cont/serial/internal/CMakeLists.txt index ab2aa7ce1..a99a94583 100644 --- a/vtkm/cont/serial/internal/CMakeLists.txt +++ b/vtkm/cont/serial/internal/CMakeLists.txt @@ -22,6 +22,7 @@ set(headers ArrayManagerExecutionSerial.h DeviceAdapterAlgorithmSerial.h DeviceAdapterTagSerial.h + ExecutionArrayInterfaceBasicSerial.h VirtualObjectTransferSerial.h ) vtkm_declare_headers(${headers}) @@ -29,4 +30,5 @@ vtkm_declare_headers(${headers}) target_sources(vtkm_cont PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/ArrayManagerExecutionSerial.cxx ${CMAKE_CURRENT_SOURCE_DIR}/DeviceAdapterAlgorithmSerial.cxx + ${CMAKE_CURRENT_SOURCE_DIR}/ExecutionArrayInterfaceBasicSerial.cxx ) diff --git a/vtkm/cont/serial/internal/DeviceAdapterAlgorithmSerial.h b/vtkm/cont/serial/internal/DeviceAdapterAlgorithmSerial.h index ec14b19b9..efb616ccc 100644 --- a/vtkm/cont/serial/internal/DeviceAdapterAlgorithmSerial.h +++ b/vtkm/cont/serial/internal/DeviceAdapterAlgorithmSerial.h @@ -281,28 +281,6 @@ public: values_output.Shrink(writePos + 1); } - template - VTKM_CONT static T ScanInclusive(const vtkm::cont::ArrayHandle& input, - vtkm::cont::ArrayHandle& output) - { - vtkm::Id numberOfValues = input.GetNumberOfValues(); - - auto inputPortal = input.PrepareForInput(Device()); - auto outputPortal = output.PrepareForOutput(numberOfValues, Device()); - - if (numberOfValues <= 0) - { - return vtkm::TypeTraits::ZeroInitialization(); - } - - std::partial_sum(vtkm::cont::ArrayPortalToIteratorBegin(inputPortal), - vtkm::cont::ArrayPortalToIteratorEnd(inputPortal), - vtkm::cont::ArrayPortalToIteratorBegin(outputPortal)); - - // Return the value at the last index in the array, which is the full sum. - return outputPortal.Get(numberOfValues - 1); - } - template VTKM_CONT static T ScanInclusive(const vtkm::cont::ArrayHandle& input, vtkm::cont::ArrayHandle& output, @@ -329,6 +307,13 @@ public: return outputPortal.Get(numberOfValues - 1); } + template + VTKM_CONT static T ScanInclusive(const vtkm::cont::ArrayHandle& input, + vtkm::cont::ArrayHandle& output) + { + return ScanInclusive(input, output, vtkm::Sum()); + } + template VTKM_CONT static T ScanExclusive(const vtkm::cont::ArrayHandle& input, vtkm::cont::ArrayHandle& output, diff --git a/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.cxx b/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.cxx new file mode 100644 index 000000000..762afaee4 --- /dev/null +++ b/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.cxx @@ -0,0 +1,36 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#include + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ +vtkm::cont::DeviceAdapterId ExecutionArrayInterfaceBasic::GetDeviceId() + const +{ + return VTKM_DEVICE_ADAPTER_SERIAL; +} + +} // namespace internal +} +} // namespace vtkm::cont diff --git a/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.h b/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.h new file mode 100644 index 000000000..32b442d72 --- /dev/null +++ b/vtkm/cont/serial/internal/ExecutionArrayInterfaceBasicSerial.h @@ -0,0 +1,50 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_cont_serial_internal_ExecutionArrayInterfaceBasicSerial_h +#define vtk_m_cont_serial_internal_ExecutionArrayInterfaceBasicSerial_h + +#include +#include + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ + +template <> +struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic + : public ExecutionArrayInterfaceBasicShareWithControl +{ + using Superclass = ExecutionArrayInterfaceBasicShareWithControl; + + VTKM_CONT + ExecutionArrayInterfaceBasic(StorageBasicBase& storage); + + VTKM_CONT + DeviceAdapterId GetDeviceId() const final; +}; + +} // namespace internal +} +} // namespace vtkm::cont + +#endif //vtk_m_cont_serial_internal_ExecutionArrayInterfaceBasicSerial_h diff --git a/vtkm/cont/tbb/internal/ArrayManagerExecutionTBB.h b/vtkm/cont/tbb/internal/ArrayManagerExecutionTBB.h index b76d7f4d6..46add0ca4 100644 --- a/vtkm/cont/tbb/internal/ArrayManagerExecutionTBB.h +++ b/vtkm/cont/tbb/internal/ArrayManagerExecutionTBB.h @@ -20,12 +20,13 @@ #ifndef vtk_m_cont_tbb_internal_ArrayManagerExecutionTBB_h #define vtk_m_cont_tbb_internal_ArrayManagerExecutionTBB_h -#include - #include #include #include +#include +#include + // These must be placed in the vtkm::cont::internal namespace so that // the template can be found. @@ -86,19 +87,6 @@ struct ExecutionPortalFactoryBasic using Superclass::CreatePortalConst; }; -template <> -struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic - : public ExecutionArrayInterfaceBasicShareWithControl -{ - using Superclass = ExecutionArrayInterfaceBasicShareWithControl; - - VTKM_CONT - ExecutionArrayInterfaceBasic(StorageBasicBase& storage); - - VTKM_CONT - virtual DeviceAdapterId GetDeviceId() const final { return VTKM_DEVICE_ADAPTER_TBB; } -}; - } // namespace internal #ifndef vtk_m_cont_tbb_internal_ArrayManagerExecutionTBB_cxx VTKM_EXPORT_ARRAYHANDLES_FOR_DEVICE_ADAPTER(DeviceAdapterTagTBB) diff --git a/vtkm/cont/tbb/internal/CMakeLists.txt b/vtkm/cont/tbb/internal/CMakeLists.txt index 79066f2db..b3cafa2f5 100644 --- a/vtkm/cont/tbb/internal/CMakeLists.txt +++ b/vtkm/cont/tbb/internal/CMakeLists.txt @@ -22,7 +22,9 @@ set(headers ArrayManagerExecutionTBB.h DeviceAdapterAlgorithmTBB.h DeviceAdapterTagTBB.h + ExecutionArrayInterfaceBasicTBB.h FunctorsTBB.h + ParallelSortTBB.h VirtualObjectTransferTBB.h ) @@ -34,7 +36,9 @@ if (VTKm_ENABLE_TBB) endif() endif() -vtkm_declare_headers(parallel_sort.h TESTABLE OFF) +vtkm_declare_headers(ParallelSortTBB.hxx + TESTABLE OFF) + vtkm_declare_headers(${headers} TESTABLE ${VTKm_ENABLE_TBB}) #----------------------------------------------------------------------------- @@ -45,4 +49,6 @@ endif() target_sources(vtkm_cont PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/ArrayManagerExecutionTBB.cxx ${CMAKE_CURRENT_SOURCE_DIR}/DeviceAdapterAlgorithmTBB.cxx + ${CMAKE_CURRENT_SOURCE_DIR}/ExecutionArrayInterfaceBasicTBB.cxx + ${CMAKE_CURRENT_SOURCE_DIR}/ParallelSortTBB.cxx ) diff --git a/vtkm/cont/tbb/internal/DeviceAdapterAlgorithmTBB.h b/vtkm/cont/tbb/internal/DeviceAdapterAlgorithmTBB.h index 157d8e055..24f4b8d43 100644 --- a/vtkm/cont/tbb/internal/DeviceAdapterAlgorithmTBB.h +++ b/vtkm/cont/tbb/internal/DeviceAdapterAlgorithmTBB.h @@ -30,6 +30,7 @@ #include #include #include +#include #include @@ -242,75 +243,37 @@ public: ScheduleTask(kernel, rangeMax); } + //1. We need functions for each of the following + + template VTKM_CONT static void Sort(vtkm::cont::ArrayHandle& values) { //this is required to get sort to work with zip handles std::less lessOp; - Sort(values, lessOp); + vtkm::cont::tbb::internal::parallel_sort(values, lessOp); } template VTKM_CONT static void Sort(vtkm::cont::ArrayHandle& values, BinaryCompare binary_compare) { - using PortalType = typename vtkm::cont::ArrayHandle::template ExecutionTypes< - vtkm::cont::DeviceAdapterTagTBB>::Portal; - PortalType arrayPortal = values.PrepareForInPlace(vtkm::cont::DeviceAdapterTagTBB()); - - using IteratorsType = vtkm::cont::ArrayPortalToIterators; - IteratorsType iterators(arrayPortal); - - internal::WrappedBinaryOperator wrappedCompare(binary_compare); - ::tbb::parallel_sort(iterators.GetBegin(), iterators.GetEnd(), wrappedCompare); + vtkm::cont::tbb::internal::parallel_sort(values, binary_compare); } template VTKM_CONT static void SortByKey(vtkm::cont::ArrayHandle& keys, vtkm::cont::ArrayHandle& values) { - SortByKey(keys, values, std::less()); + vtkm::cont::tbb::internal::parallel_sort_bykey(keys, values, std::less()); } - template + template VTKM_CONT static void SortByKey(vtkm::cont::ArrayHandle& keys, vtkm::cont::ArrayHandle& values, - Compare comp) + BinaryCompare binary_compare) { - using KeyType = vtkm::cont::ArrayHandle; - VTKM_CONSTEXPR bool larger_than_64bits = sizeof(U) > sizeof(vtkm::Int64); - if (larger_than_64bits) - { - /// More efficient sort: - /// Move value indexes when sorting and reorder the value array at last - - using ValueType = vtkm::cont::ArrayHandle; - using IndexType = vtkm::cont::ArrayHandle; - using ZipHandleType = vtkm::cont::ArrayHandleZip; - - IndexType indexArray; - ValueType valuesScattered; - const vtkm::Id size = values.GetNumberOfValues(); - - Copy(ArrayHandleIndex(keys.GetNumberOfValues()), indexArray); - - ZipHandleType zipHandle = vtkm::cont::make_ArrayHandleZip(keys, indexArray); - Sort(zipHandle, vtkm::cont::internal::KeyCompare(comp)); - - tbb::ScatterPortal(values.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), - indexArray.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), - valuesScattered.PrepareForOutput(size, vtkm::cont::DeviceAdapterTagTBB())); - - Copy(valuesScattered, values); - } - else - { - using ValueType = vtkm::cont::ArrayHandle; - using ZipHandleType = vtkm::cont::ArrayHandleZip; - - ZipHandleType zipHandle = vtkm::cont::make_ArrayHandleZip(keys, values); - Sort(zipHandle, vtkm::cont::internal::KeyCompare(comp)); - } + vtkm::cont::tbb::internal::parallel_sort_bykey(keys, values, binary_compare); } template diff --git a/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.cxx b/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.cxx new file mode 100644 index 000000000..9920c599e --- /dev/null +++ b/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.cxx @@ -0,0 +1,35 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#include + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ +vtkm::cont::DeviceAdapterId ExecutionArrayInterfaceBasic::GetDeviceId() const +{ + return VTKM_DEVICE_ADAPTER_TBB; +} + +} // namespace internal +} +} // namespace vtkm::cont diff --git a/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.h b/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.h new file mode 100644 index 000000000..6b980d97a --- /dev/null +++ b/vtkm/cont/tbb/internal/ExecutionArrayInterfaceBasicTBB.h @@ -0,0 +1,53 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_cont_tbb_internal_ExecutionArrayInterfaceBasicTBB_h +#define vtk_m_cont_tbb_internal_ExecutionArrayInterfaceBasicTBB_h + +#include +#include + +// These must be placed in the vtkm::cont::internal namespace so that +// the template can be found. + +namespace vtkm +{ +namespace cont +{ +namespace internal +{ + +template <> +struct VTKM_CONT_EXPORT ExecutionArrayInterfaceBasic + : public ExecutionArrayInterfaceBasicShareWithControl +{ + using Superclass = ExecutionArrayInterfaceBasicShareWithControl; + + VTKM_CONT + ExecutionArrayInterfaceBasic(StorageBasicBase& storage); + + VTKM_CONT + DeviceAdapterId GetDeviceId() const final; +}; + +} // namespace internal +} +} // namespace vtkm::cont + +#endif //vtk_m_cont_tbb_internal_ExecutionArrayInterfaceBasicTBB_h diff --git a/vtkm/cont/tbb/internal/ParallelSortTBB.cxx b/vtkm/cont/tbb/internal/ParallelSortTBB.cxx new file mode 100644 index 000000000..7f61dffca --- /dev/null +++ b/vtkm/cont/tbb/internal/ParallelSortTBB.cxx @@ -0,0 +1,958 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= + +// Copyright 2010, Takuya Akiba +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Takuya Akiba nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Modifications of Takuya Akiba's original GitHub source code for inclusion +// in VTK-m: +// +// - Changed parallel threading from OpenMP to TBB tasks +// - Added minimum threshold for parallel, will instead invoke serial radix sort (kxsort) +// - Added std::greater and std::less to interface for descending order sorts +// - Added linear scaling of threads used by the algorithm for more stable performance +// on machines with lots of available threads (KNL and Haswell) +// +// This file contains an implementation of Satish parallel radix sort +// as documented in the following citation: +// +// Fast sort on CPUs and GPUs: a case for bandwidth oblivious SIMD sort. +// N. Satish, C. Kim, J. Chhugani, A. D. Nguyen, V. W. Lee, D. Kim, and P. Dubey. +// In Proc. SIGMOD, pages 351–362, 2010 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +VTKM_THIRDPARTY_PRE_INCLUDE + +#include + +#if defined(VTKM_MSVC) + +// TBB's header include a #pragma comment(lib,"tbb.lib") line to make all +// consuming libraries link to tbb, this is bad behavior in a header +// based project +#pragma push_macro("__TBB_NO_IMPLICITLINKAGE") +#define __TBB_NO_IMPLICIT_LINKAGE 1 + +#endif // defined(VTKM_MSVC) + +// TBB includes windows.h, so instead we want to include windows.h with the +// correct settings so that we don't clobber any existing function +#include + +#include +#include + +#if defined(VTKM_MSVC) +#pragma pop_macro("__TBB_NO_IMPLICITLINKAGE") +#endif + +namespace vtkm +{ +namespace cont +{ +namespace tbb +{ +namespace internal +{ + +const size_t MIN_BYTES_FOR_PARALLEL = 400000; +const size_t BYTES_FOR_MAX_PARALLELISM = 4000000; +const size_t MAX_CORES = ::tbb::tbb_thread::hardware_concurrency(); +const double CORES_PER_BYTE = + double(MAX_CORES - 1) / double(BYTES_FOR_MAX_PARALLELISM - MIN_BYTES_FOR_PARALLEL); +const double Y_INTERCEPT = 1.0 - CORES_PER_BYTE * MIN_BYTES_FOR_PARALLEL; + +namespace utility +{ +// Return the number of threads that would be executed in parallel regions +inline size_t GetMaxThreads(size_t num_bytes) +{ + size_t num_cores = (size_t)(CORES_PER_BYTE * double(num_bytes) + Y_INTERCEPT); + if (num_cores < 1) + { + return 1; + } + if (num_cores > MAX_CORES) + { + return MAX_CORES; + } + return num_cores; +} +} // namespace utility + +namespace internal +{ +// Size of the software managed buffer +const size_t kOutBufferSize = 32; + +// Ascending order radix sort is a no-op +template +struct ParallelRadixCompareInternal +{ + inline static void reverse(UnsignedType& t) { (void)t; } +}; + +// Handle descending order radix sort +template +struct ParallelRadixCompareInternal, + ValueManager, + Base> +{ + inline static void reverse(UnsignedType& t) { t = ((1 << Base) - 1) - t; } +}; + +// The algorithm is implemented in this internal class +template +class ParallelRadixSortInternal +{ +public: + using CompareInternal = + ParallelRadixCompareInternal; + + ParallelRadixSortInternal(); + ~ParallelRadixSortInternal(); + + void Init(PlainType* data, size_t num_elems); + + PlainType* Sort(PlainType* data, ValueManager* value_manager); + + static void InitAndSort(PlainType* data, size_t num_elems, ValueManager* value_manager); + +private: + CompareInternal compare_internal_; + size_t num_elems_; + size_t num_threads_; + + UnsignedType* tmp_; + size_t** histo_; + UnsignedType*** out_buf_; + size_t** out_buf_n_; + + size_t *pos_bgn_, *pos_end_; + ValueManager* value_manager_; + + void DeleteAll(); + + UnsignedType* SortInternal(UnsignedType* data, ValueManager* value_manager); + + // Compute |pos_bgn_| and |pos_end_| (associated ranges for each threads) + void ComputeRanges(); + + // First step of each iteration of sorting + // Compute the histogram of |src| using bits in [b, b + Base) + void ComputeHistogram(unsigned int b, UnsignedType* src); + + // Second step of each iteration of sorting + // Scatter elements of |src| to |dst| using the histogram + void Scatter(unsigned int b, UnsignedType* src, UnsignedType* dst); +}; + +template +ParallelRadixSortInternal:: + ParallelRadixSortInternal() + : num_elems_(0) + , num_threads_(0) + , tmp_(NULL) + , histo_(NULL) + , out_buf_(NULL) + , out_buf_n_(NULL) + , pos_bgn_(NULL) + , pos_end_(NULL) +{ + assert(sizeof(PlainType) == sizeof(UnsignedType)); +} + +template +ParallelRadixSortInternal:: + ~ParallelRadixSortInternal() +{ + DeleteAll(); +} + +template +void ParallelRadixSortInternal:: + DeleteAll() +{ + delete[] tmp_; + tmp_ = NULL; + + for (size_t i = 0; i < num_threads_; ++i) + delete[] histo_[i]; + delete[] histo_; + histo_ = NULL; + + for (size_t i = 0; i < num_threads_; ++i) + { + for (size_t j = 0; j < 1 << Base; ++j) + { + delete[] out_buf_[i][j]; + } + delete[] out_buf_n_[i]; + delete[] out_buf_[i]; + } + delete[] out_buf_; + delete[] out_buf_n_; + out_buf_ = NULL; + out_buf_n_ = NULL; + + delete[] pos_bgn_; + delete[] pos_end_; + pos_bgn_ = pos_end_ = NULL; + + num_elems_ = 0; + num_threads_ = 0; +} + +template +void ParallelRadixSortInternal:: + Init(PlainType* data, size_t num_elems) +{ + (void)data; + DeleteAll(); + + num_elems_ = num_elems; + + num_threads_ = utility::GetMaxThreads(num_elems_ * sizeof(PlainType)); + + tmp_ = new UnsignedType[num_elems_]; + histo_ = new size_t*[num_threads_]; + for (size_t i = 0; i < num_threads_; ++i) + { + histo_[i] = new size_t[1 << Base]; + } + + out_buf_ = new UnsignedType**[num_threads_]; + out_buf_n_ = new size_t*[num_threads_]; + for (size_t i = 0; i < num_threads_; ++i) + { + out_buf_[i] = new UnsignedType*[1 << Base]; + out_buf_n_[i] = new size_t[1 << Base]; + for (size_t j = 0; j < 1 << Base; ++j) + { + out_buf_[i][j] = new UnsignedType[kOutBufferSize]; + } + } + + pos_bgn_ = new size_t[num_threads_]; + pos_end_ = new size_t[num_threads_]; +} + +template +PlainType* +ParallelRadixSortInternal::Sort( + PlainType* data, + ValueManager* value_manager) +{ + UnsignedType* src = reinterpret_cast(data); + UnsignedType* res = SortInternal(src, value_manager); + return reinterpret_cast(res); +} + +template +void ParallelRadixSortInternal:: + InitAndSort(PlainType* data, size_t num_elems, ValueManager* value_manager) +{ + ParallelRadixSortInternal prs; + prs.Init(data, num_elems); + const PlainType* res = prs.Sort(data, value_manager); + if (res != data) + { + for (size_t i = 0; i < num_elems; ++i) + data[i] = res[i]; + } +} + +template +UnsignedType* +ParallelRadixSortInternal:: + SortInternal(UnsignedType* data, ValueManager* value_manager) +{ + + value_manager_ = value_manager; + + // Compute |pos_bgn_| and |pos_end_| + ComputeRanges(); + + // Iterate from lower bits to higher bits + const size_t bits = CHAR_BIT * sizeof(UnsignedType); + UnsignedType *src = data, *dst = tmp_; + for (unsigned int b = 0; b < bits; b += Base) + { + ComputeHistogram(b, src); + Scatter(b, src, dst); + + std::swap(src, dst); + value_manager->Next(); + } + + return src; +} + +template +void ParallelRadixSortInternal:: + ComputeRanges() +{ + pos_bgn_[0] = 0; + for (size_t i = 0; i < num_threads_ - 1; ++i) + { + const size_t t = (num_elems_ - pos_bgn_[i]) / (num_threads_ - i); + pos_bgn_[i + 1] = pos_end_[i] = pos_bgn_[i] + t; + } + pos_end_[num_threads_ - 1] = num_elems_; +} + +template +class RunTask : public ::tbb::task +{ +public: + RunTask(size_t binary_tree_height, + size_t binary_tree_position, + Function f, + size_t num_elems, + size_t num_threads) + : binary_tree_height_(binary_tree_height) + , binary_tree_position_(binary_tree_position) + , f_(f) + , num_elems_(num_elems) + , num_threads_(num_threads) + { + } + + ::tbb::task* execute() + { + size_t num_nodes_at_current_height = (size_t)pow(2, (double)binary_tree_height_); + if (num_threads_ <= num_nodes_at_current_height) + { + const size_t my_id = binary_tree_position_ - num_nodes_at_current_height; + if (my_id < num_threads_) + { + f_(my_id); + } + return NULL; + } + else + { + ::tbb::empty_task& p = *new (task::allocate_continuation())::tbb::empty_task(); + RunTask& left = *new (p.allocate_child()) RunTask( + binary_tree_height_ + 1, 2 * binary_tree_position_, f_, num_elems_, num_threads_); + RunTask& right = *new (p.allocate_child()) RunTask( + binary_tree_height_ + 1, 2 * binary_tree_position_ + 1, f_, num_elems_, num_threads_); + p.set_ref_count(2); + task::spawn(left); + task::spawn(right); + return NULL; + } + } + +private: + size_t binary_tree_height_; + size_t binary_tree_position_; + Function f_; + size_t num_elems_; + size_t num_threads_; +}; + +template +void ParallelRadixSortInternal:: + ComputeHistogram(unsigned int b, UnsignedType* src) +{ + // Compute local histogram + + auto lambda = [=](const size_t my_id) { + const size_t my_bgn = pos_bgn_[my_id]; + const size_t my_end = pos_end_[my_id]; + size_t* my_histo = histo_[my_id]; + + memset(my_histo, 0, sizeof(size_t) * (1 << Base)); + for (size_t i = my_bgn; i < my_end; ++i) + { + const UnsignedType s = Encoder::encode(src[i]); + UnsignedType t = (s >> b) & ((1 << Base) - 1); + compare_internal_.reverse(t); + ++my_histo[t]; + } + }; + + typedef RunTask> RunTaskType; + + RunTaskType& root = + *new (::tbb::task::allocate_root()) RunTaskType(0, 1, lambda, num_elems_, num_threads_); + + ::tbb::task::spawn_root_and_wait(root); + + // Compute global histogram + size_t s = 0; + for (size_t i = 0; i < 1 << Base; ++i) + { + for (size_t j = 0; j < num_threads_; ++j) + { + const size_t t = s + histo_[j][i]; + histo_[j][i] = s; + s = t; + } + } +} + +template +void ParallelRadixSortInternal:: + Scatter(unsigned int b, UnsignedType* src, UnsignedType* dst) +{ + + auto lambda = [=](const size_t my_id) { + const size_t my_bgn = pos_bgn_[my_id]; + const size_t my_end = pos_end_[my_id]; + size_t* my_histo = histo_[my_id]; + UnsignedType** my_buf = out_buf_[my_id]; + size_t* my_buf_n = out_buf_n_[my_id]; + + memset(my_buf_n, 0, sizeof(size_t) * (1 << Base)); + for (size_t i = my_bgn; i < my_end; ++i) + { + const UnsignedType s = Encoder::encode(src[i]); + UnsignedType t = (s >> b) & ((1 << Base) - 1); + compare_internal_.reverse(t); + my_buf[t][my_buf_n[t]] = src[i]; + value_manager_->Push(my_id, t, my_buf_n[t], i); + ++my_buf_n[t]; + + if (my_buf_n[t] == kOutBufferSize) + { + size_t p = my_histo[t]; + for (size_t j = 0; j < kOutBufferSize; ++j) + { + size_t tp = p++; + dst[tp] = my_buf[t][j]; + } + value_manager_->Flush(my_id, t, kOutBufferSize, my_histo[t]); + + my_histo[t] += kOutBufferSize; + my_buf_n[t] = 0; + } + } + + // Flush everything + for (size_t i = 0; i < 1 << Base; ++i) + { + size_t p = my_histo[i]; + for (size_t j = 0; j < my_buf_n[i]; ++j) + { + size_t tp = p++; + dst[tp] = my_buf[i][j]; + } + value_manager_->Flush(my_id, i, my_buf_n[i], my_histo[i]); + } + }; + + typedef RunTask> RunTaskType; + + RunTaskType& root = + *new (::tbb::task::allocate_root()) RunTaskType(0, 1, lambda, num_elems_, num_threads_); + + ::tbb::task::spawn_root_and_wait(root); +} +} // namespace internal + +// Encoders encode signed/unsigned integers and floating point numbers +// to correctly ordered unsigned integers +namespace encoder +{ +class EncoderDummy +{ +}; + +class EncoderUnsigned +{ +public: + template + inline static UnsignedType encode(UnsignedType x) + { + return x; + } +}; + +class EncoderSigned +{ +public: + template + inline static UnsignedType encode(UnsignedType x) + { + return x ^ (UnsignedType(1) << (CHAR_BIT * sizeof(UnsignedType) - 1)); + } +}; + +class EncoderDecimal +{ +public: + template + inline static UnsignedType encode(UnsignedType x) + { + static const size_t bits = CHAR_BIT * sizeof(UnsignedType); + const UnsignedType a = x >> (bits - 1); + const UnsignedType b = (-static_cast(a)) | (UnsignedType(1) << (bits - 1)); + return x ^ b; + } +}; +} // namespace encoder + +// Value managers are used to generalize the sorting algorithm +// to sorting of keys and sorting of pairs +namespace value_manager +{ +class DummyValueManager +{ +public: + inline void Push(int thread, size_t bucket, size_t num, size_t from_pos) + { + (void)thread; + (void)bucket; + (void)num; + (void)from_pos; + } + + inline void Flush(int thread, size_t bucket, size_t num, size_t to_pos) + { + (void)thread; + (void)bucket; + (void)num; + (void)to_pos; + } + + void Next() {} +}; + +template +class PairValueManager +{ +public: + PairValueManager() + : max_elems_(0) + , max_threads_(0) + , original_(NULL) + , tmp_(NULL) + , src_(NULL) + , dst_(NULL) + , out_buf_(NULL) + { + } + + ~PairValueManager() { DeleteAll(); } + + void Init(size_t max_elems); + + void Start(ValueType* original, size_t num_elems) + { + assert(num_elems <= max_elems_); + src_ = original_ = original; + dst_ = tmp_; + } + + inline void Push(int thread, size_t bucket, size_t num, size_t from_pos) + { + out_buf_[thread][bucket][num] = src_[from_pos]; + } + + inline void Flush(int thread, size_t bucket, size_t num, size_t to_pos) + { + for (size_t i = 0; i < num; ++i) + { + dst_[to_pos++] = out_buf_[thread][bucket][i]; + } + } + + void Next() { std::swap(src_, dst_); } + + ValueType* GetResult() { return src_; } +private: + size_t max_elems_; + int max_threads_; + + static const size_t kOutBufferSize = internal::kOutBufferSize; + ValueType *original_, *tmp_; + ValueType *src_, *dst_; + ValueType*** out_buf_; + + void DeleteAll(); +}; + +template +void PairValueManager::Init(size_t max_elems) +{ + DeleteAll(); + + max_elems_ = max_elems; + max_threads_ = utility::GetMaxThreads(max_elems_ * sizeof(PlainType)); + + tmp_ = new ValueType[max_elems]; + + out_buf_ = new ValueType**[max_threads_]; + for (int i = 0; i < max_threads_; ++i) + { + out_buf_[i] = new ValueType*[1 << Base]; + for (size_t j = 0; j < 1 << Base; ++j) + { + out_buf_[i][j] = new ValueType[kOutBufferSize]; + } + } +} + +template +void PairValueManager::DeleteAll() +{ + delete[] tmp_; + tmp_ = NULL; + + for (int i = 0; i < max_threads_; ++i) + { + for (size_t j = 0; j < 1 << Base; ++j) + { + delete[] out_buf_[i][j]; + } + delete[] out_buf_[i]; + } + delete[] out_buf_; + out_buf_ = NULL; + + max_elems_ = 0; + max_threads_ = 0; +} +} // namespace value_manager + +// Frontend class for sorting keys +template +class KeySort +{ + using DummyValueManager = value_manager::DummyValueManager; + using Internal = internal::ParallelRadixSortInternal; + +public: + void InitAndSort(PlainType* data, size_t num_elems, const CompareType& comp) + { + (void)comp; + DummyValueManager dvm; + Internal::InitAndSort(data, num_elems, &dvm); + } +}; + +// Frontend class for sorting pairs +template +class PairSort +{ + using ValueManager = value_manager::PairValueManager; + using Internal = internal:: + ParallelRadixSortInternal; + +public: + void InitAndSort(PlainType* keys, ValueType* vals, size_t num_elems, const CompareType& comp) + { + (void)comp; + ValueManager vm; + vm.Init(num_elems); + vm.Start(vals, num_elems); + Internal::InitAndSort(keys, num_elems, &vm); + ValueType* res_vals = vm.GetResult(); + if (res_vals != vals) + { + for (size_t i = 0; i < num_elems; ++i) + { + vals[i] = res_vals[i]; + } + } + } + +private: +}; + +#define KEY_SORT_CASE(plain_type, compare_type, unsigned_type, encoder_type) \ + template <> \ + class KeySort \ + : public KeySort \ + { \ + }; \ + template \ + class PairSort \ + : public PairSort \ + { \ + }; + +// Unsigned integers +KEY_SORT_CASE(unsigned int, std::less, unsigned int, Unsigned); +KEY_SORT_CASE(unsigned int, std::greater, unsigned int, Unsigned); +KEY_SORT_CASE(unsigned short int, std::less, unsigned short int, Unsigned); +KEY_SORT_CASE(unsigned short int, std::greater, unsigned short int, Unsigned); +KEY_SORT_CASE(unsigned long int, std::less, unsigned long int, Unsigned); +KEY_SORT_CASE(unsigned long int, std::greater, unsigned long int, Unsigned); +KEY_SORT_CASE(unsigned long long int, + std::less, + unsigned long long int, + Unsigned); +KEY_SORT_CASE(unsigned long long int, + std::greater, + unsigned long long int, + Unsigned); + +// Unsigned char +KEY_SORT_CASE(unsigned char, std::less, unsigned char, Unsigned); +KEY_SORT_CASE(unsigned char, std::greater, unsigned char, Unsigned); +KEY_SORT_CASE(char16_t, std::less, uint16_t, Unsigned); +KEY_SORT_CASE(char16_t, std::greater, uint16_t, Unsigned); +KEY_SORT_CASE(char32_t, std::less, uint32_t, Unsigned); +KEY_SORT_CASE(char32_t, std::greater, uint32_t, Unsigned); +KEY_SORT_CASE(wchar_t, std::less, uint32_t, Unsigned); +KEY_SORT_CASE(wchar_t, std::greater, uint32_t, Unsigned); + +// Signed integers +KEY_SORT_CASE(char, std::less, unsigned char, Signed); +KEY_SORT_CASE(char, std::greater, unsigned char, Signed); +KEY_SORT_CASE(short, std::less, unsigned short, Signed); +KEY_SORT_CASE(short, std::greater, unsigned short, Signed); +KEY_SORT_CASE(int, std::less, unsigned int, Signed); +KEY_SORT_CASE(int, std::greater, unsigned int, Signed); +KEY_SORT_CASE(long, std::less, unsigned long, Signed); +KEY_SORT_CASE(long, std::greater, unsigned long, Signed); +KEY_SORT_CASE(long long, std::less, unsigned long long, Signed); +KEY_SORT_CASE(long long, std::greater, unsigned long long, Signed); + +// |signed char| and |char| are treated as different types +KEY_SORT_CASE(signed char, std::less, unsigned char, Signed); +KEY_SORT_CASE(signed char, std::greater, unsigned char, Signed); + +// Floating point numbers +KEY_SORT_CASE(float, std::less, uint32_t, Decimal); +KEY_SORT_CASE(float, std::greater, uint32_t, Decimal); +KEY_SORT_CASE(double, std::less, uint64_t, Decimal); +KEY_SORT_CASE(double, std::greater, uint64_t, Decimal); + +#undef KEY_SORT_CASE + +template +struct run_kx_radix_sort_keys +{ + static void run(T* data, size_t num_elems, const CompareType& comp) + { + std::sort(data, data + num_elems, comp); + } +}; + +#define KX_SORT_KEYS(key_type) \ + template <> \ + struct run_kx_radix_sort_keys> \ + { \ + static void run(key_type* data, size_t num_elems, const std::less& comp) \ + { \ + (void)comp; \ + kx::radix_sort(data, data + num_elems); \ + } \ + }; + +KX_SORT_KEYS(unsigned short int); +KX_SORT_KEYS(int); +KX_SORT_KEYS(unsigned int); +KX_SORT_KEYS(long int); +KX_SORT_KEYS(unsigned long int); +KX_SORT_KEYS(long long int); +KX_SORT_KEYS(unsigned long long int); +KX_SORT_KEYS(unsigned char); + +#undef KX_SORT_KEYS + +template +bool use_serial_sort_keys(T* data, size_t num_elems, const CompareType& comp) +{ + size_t total_bytes = (num_elems) * sizeof(T); + if (total_bytes < MIN_BYTES_FOR_PARALLEL) + { + run_kx_radix_sort_keys::run(data, num_elems, comp); + return true; + } + return false; +} + +// Generate radix sort interfaces for key and key value sorts. +#define VTKM_TBB_SORT_EXPORT(key_type) \ + void parallel_radix_sort_key_values( \ + key_type* keys, vtkm::Id* vals, size_t num_elems, const std::greater& comp) \ + { \ + PairSort> ps; \ + ps.InitAndSort(keys, vals, num_elems, comp); \ + } \ + void parallel_radix_sort_key_values( \ + key_type* keys, vtkm::Id* vals, size_t num_elems, const std::less& comp) \ + { \ + PairSort> ps; \ + ps.InitAndSort(keys, vals, num_elems, comp); \ + } \ + void parallel_radix_sort(key_type* data, size_t num_elems, const std::greater& comp) \ + { \ + if (!use_serial_sort_keys(data, num_elems, comp)) \ + { \ + KeySort> ks; \ + ks.InitAndSort(data, num_elems, comp); \ + } \ + } \ + void parallel_radix_sort(key_type* data, size_t num_elems, const std::less& comp) \ + { \ + if (!use_serial_sort_keys(data, num_elems, comp)) \ + { \ + KeySort> ks; \ + ks.InitAndSort(data, num_elems, comp); \ + } \ + } + +VTKM_TBB_SORT_EXPORT(short int); +VTKM_TBB_SORT_EXPORT(unsigned short int); +VTKM_TBB_SORT_EXPORT(int); +VTKM_TBB_SORT_EXPORT(unsigned int); +VTKM_TBB_SORT_EXPORT(long int); +VTKM_TBB_SORT_EXPORT(unsigned long int); +VTKM_TBB_SORT_EXPORT(long long int); +VTKM_TBB_SORT_EXPORT(unsigned long long int); +VTKM_TBB_SORT_EXPORT(unsigned char); +VTKM_TBB_SORT_EXPORT(signed char); +VTKM_TBB_SORT_EXPORT(char); +VTKM_TBB_SORT_EXPORT(char16_t); +VTKM_TBB_SORT_EXPORT(char32_t); +VTKM_TBB_SORT_EXPORT(wchar_t); +VTKM_TBB_SORT_EXPORT(float); +VTKM_TBB_SORT_EXPORT(double); + +#undef VTKM_TBB_SORT_EXPORT + +VTKM_THIRDPARTY_POST_INCLUDE +} +} +} +} diff --git a/vtkm/cont/tbb/internal/ParallelSortTBB.h b/vtkm/cont/tbb/internal/ParallelSortTBB.h new file mode 100644 index 000000000..13100bfdb --- /dev/null +++ b/vtkm/cont/tbb/internal/ParallelSortTBB.h @@ -0,0 +1,309 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2017 UT-Battelle, LLC. +// Copyright 2017 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ + +#ifndef vtk_m_cont_tbb_internal_ParallelSort_h +#define vtk_m_cont_tbb_internal_ParallelSort_h + +#include +#include +#include + +#include +#include +#include +#include + +#include + +namespace vtkm +{ +namespace cont +{ +namespace tbb +{ +namespace internal +{ +struct RadixSortTag +{ +}; +struct PSortTag +{ +}; + +template +struct is_valid_compare_type : std::integral_constant +{ +}; +template +struct is_valid_compare_type> : std::integral_constant +{ +}; +template +struct is_valid_compare_type> : std::integral_constant +{ +}; +template <> +struct is_valid_compare_type : std::integral_constant +{ +}; +template <> +struct is_valid_compare_type : std::integral_constant +{ +}; +template +BComp&& get_std_compare(BComp&& b, T&&) +{ + return std::forward(b); +} +template +std::less get_std_compare(vtkm::SortLess, T&&) +{ + return std::less{}; +} +template +std::greater get_std_compare(vtkm::SortGreater, T&&) +{ + return std::greater{}; +} + + +template +struct sort_tag_type +{ + using type = PSortTag; +}; +template +struct sort_tag_type +{ + using PrimT = std::is_arithmetic; + using LongDT = std::is_same; + using BComp = is_valid_compare_type; + using type = typename std::conditional::type; +}; + +template +struct sortbykey_tag_type +{ + using type = PSortTag; +}; +template +struct sortbykey_tag_type +{ + using PrimT = std::is_arithmetic; + using PrimU = std::is_arithmetic; + using LongDT = std::is_same; + using BComp = is_valid_compare_type; + using type = + typename std::conditional::type; +}; + + +#define VTKM_TBB_SORT_EXPORT(key_type) \ + VTKM_CONT_EXPORT void parallel_radix_sort( \ + key_type* data, size_t num_elems, const std::greater& comp); \ + VTKM_CONT_EXPORT void parallel_radix_sort( \ + key_type* data, size_t num_elems, const std::less& comp); \ + VTKM_CONT_EXPORT void parallel_radix_sort_key_values( \ + key_type* keys, vtkm::Id* vals, size_t num_elems, const std::greater& comp); \ + VTKM_CONT_EXPORT void parallel_radix_sort_key_values( \ + key_type* keys, vtkm::Id* vals, size_t num_elems, const std::less& comp); + +// Generate radix sort interfaces for key and key value sorts. +VTKM_TBB_SORT_EXPORT(short int); +VTKM_TBB_SORT_EXPORT(unsigned short int); +VTKM_TBB_SORT_EXPORT(int); +VTKM_TBB_SORT_EXPORT(unsigned int); +VTKM_TBB_SORT_EXPORT(long int); +VTKM_TBB_SORT_EXPORT(unsigned long int); +VTKM_TBB_SORT_EXPORT(long long int); +VTKM_TBB_SORT_EXPORT(unsigned long long int); +VTKM_TBB_SORT_EXPORT(unsigned char); +VTKM_TBB_SORT_EXPORT(signed char); +VTKM_TBB_SORT_EXPORT(char); +VTKM_TBB_SORT_EXPORT(char16_t); +VTKM_TBB_SORT_EXPORT(char32_t); +VTKM_TBB_SORT_EXPORT(wchar_t); +VTKM_TBB_SORT_EXPORT(float); +VTKM_TBB_SORT_EXPORT(double); +#undef VTKM_TBB_SORT_EXPORT + +template +void parallel_sort(vtkm::cont::ArrayHandle& values, BinaryCompare binary_compare) +{ + using SortAlgorithmTag = typename sort_tag_type::type; + parallel_sort(values, binary_compare, SortAlgorithmTag{}); +} +template +void parallel_sort(HandleType& values, BinaryCompare binary_compare, PSortTag) +{ + auto arrayPortal = values.PrepareForInPlace(vtkm::cont::DeviceAdapterTagTBB()); + + using IteratorsType = vtkm::cont::ArrayPortalToIterators; + IteratorsType iterators(arrayPortal); + + internal::WrappedBinaryOperator wrappedCompare(binary_compare); + ::tbb::parallel_sort(iterators.GetBegin(), iterators.GetEnd(), wrappedCompare); +} +template +void parallel_sort(vtkm::cont::ArrayHandle& values, + BinaryCompare binary_compare, + RadixSortTag) +{ + auto c = get_std_compare(binary_compare, T{}); + parallel_radix_sort( + values.GetStorage().GetArray(), static_cast(values.GetNumberOfValues()), c); +} + +template +void parallel_sort_bykey(vtkm::cont::ArrayHandle& keys, + vtkm::cont::ArrayHandle& values, + BinaryCompare binary_compare) +{ + using SortAlgorithmTag = + typename sortbykey_tag_type::type; + parallel_sort_bykey(keys, values, binary_compare, SortAlgorithmTag{}); +} +template +void parallel_sort_bykey(vtkm::cont::ArrayHandle& keys, + vtkm::cont::ArrayHandle& values, + BinaryCompare binary_compare, + PSortTag) +{ + using KeyType = vtkm::cont::ArrayHandle; + VTKM_CONSTEXPR bool larger_than_64bits = sizeof(U) > sizeof(vtkm::Int64); + if (larger_than_64bits) + { + /// More efficient sort: + /// Move value indexes when sorting and reorder the value array at last + + using ValueType = vtkm::cont::ArrayHandle; + using IndexType = vtkm::cont::ArrayHandle; + using ZipHandleType = vtkm::cont::ArrayHandleZip; + + IndexType indexArray; + ValueType valuesScattered; + const vtkm::Id size = values.GetNumberOfValues(); + + { + auto handle = ArrayHandleIndex(keys.GetNumberOfValues()); + auto inputPortal = handle.PrepareForInput(DeviceAdapterTagTBB()); + auto outputPortal = + indexArray.PrepareForOutput(keys.GetNumberOfValues(), DeviceAdapterTagTBB()); + tbb::CopyPortals(inputPortal, outputPortal, 0, 0, keys.GetNumberOfValues()); + } + + ZipHandleType zipHandle = vtkm::cont::make_ArrayHandleZip(keys, indexArray); + parallel_sort(zipHandle, + vtkm::cont::internal::KeyCompare(binary_compare), + PSortTag()); + + tbb::ScatterPortal(values.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), + indexArray.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), + valuesScattered.PrepareForOutput(size, vtkm::cont::DeviceAdapterTagTBB())); + + { + auto inputPortal = valuesScattered.PrepareForInput(DeviceAdapterTagTBB()); + auto outputPortal = + values.PrepareForOutput(valuesScattered.GetNumberOfValues(), DeviceAdapterTagTBB()); + tbb::CopyPortals(inputPortal, outputPortal, 0, 0, valuesScattered.GetNumberOfValues()); + } + } + else + { + using ValueType = vtkm::cont::ArrayHandle; + using ZipHandleType = vtkm::cont::ArrayHandleZip; + + ZipHandleType zipHandle = vtkm::cont::make_ArrayHandleZip(keys, values); + parallel_sort( + zipHandle, vtkm::cont::internal::KeyCompare(binary_compare), PSortTag{}); + } +} +template +void parallel_sort_bykey(vtkm::cont::ArrayHandle& keys, + vtkm::cont::ArrayHandle& values, + BinaryCompare binary_compare, + RadixSortTag) +{ + auto c = get_std_compare(binary_compare, T{}); + parallel_radix_sort_key_values(keys.GetStorage().GetArray(), + values.GetStorage().GetArray(), + static_cast(keys.GetNumberOfValues()), + c); +} +template +void parallel_sort_bykey(vtkm::cont::ArrayHandle& keys, + vtkm::cont::ArrayHandle& values, + BinaryCompare binary_compare, + RadixSortTag) +{ + using KeyType = vtkm::cont::ArrayHandle; + using ValueType = vtkm::cont::ArrayHandle; + using IndexType = vtkm::cont::ArrayHandle; + using ZipHandleType = vtkm::cont::ArrayHandleZip; + + IndexType indexArray; + ValueType valuesScattered; + const vtkm::Id size = values.GetNumberOfValues(); + + { + auto handle = ArrayHandleIndex(keys.GetNumberOfValues()); + auto inputPortal = handle.PrepareForInput(DeviceAdapterTagTBB()); + auto outputPortal = + indexArray.PrepareForOutput(keys.GetNumberOfValues(), DeviceAdapterTagTBB()); + tbb::CopyPortals(inputPortal, outputPortal, 0, 0, keys.GetNumberOfValues()); + } + + if (static_cast(sizeof(T)) * keys.GetNumberOfValues() > 400000) + { + parallel_sort_bykey(keys, indexArray, binary_compare); + } + else + { + ZipHandleType zipHandle = vtkm::cont::make_ArrayHandleZip(keys, indexArray); + parallel_sort(zipHandle, + vtkm::cont::internal::KeyCompare(binary_compare), + PSortTag{}); + } + + tbb::ScatterPortal(values.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), + indexArray.PrepareForInput(vtkm::cont::DeviceAdapterTagTBB()), + valuesScattered.PrepareForOutput(size, vtkm::cont::DeviceAdapterTagTBB())); + + { + auto inputPortal = valuesScattered.PrepareForInput(DeviceAdapterTagTBB()); + auto outputPortal = + values.PrepareForOutput(valuesScattered.GetNumberOfValues(), DeviceAdapterTagTBB()); + tbb::CopyPortals(inputPortal, outputPortal, 0, 0, valuesScattered.GetNumberOfValues()); + } +} +} +} +} +} + +#endif // vtk_m_cont_tbb_internal_ParallelSort_h diff --git a/vtkm/cont/tbb/internal/parallel_sort.h b/vtkm/cont/tbb/internal/ParallelSortTBB.hxx similarity index 100% rename from vtkm/cont/tbb/internal/parallel_sort.h rename to vtkm/cont/tbb/internal/ParallelSortTBB.hxx diff --git a/vtkm/cont/tbb/internal/kxsort.h b/vtkm/cont/tbb/internal/kxsort.h new file mode 100644 index 000000000..f628612ea --- /dev/null +++ b/vtkm/cont/tbb/internal/kxsort.h @@ -0,0 +1,176 @@ +/* The MIT License + Copyright (c) 2016 Dinghua Li + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +#ifndef KXSORT_H__ +#define KXSORT_H__ + +#include +#include + +namespace kx +{ + +static const int kRadixBits = 8; +static const size_t kInsertSortThreshold = 64; +static const int kRadixMask = (1 << kRadixBits) - 1; +static const int kRadixBin = 1 << kRadixBits; + +//================= HELPING FUNCTIONS ==================== + +template +struct RadixTraitsUnsigned +{ + static const int nBytes = sizeof(T); + int kth_byte(const T& x, int k) { return (x >> (kRadixBits * k)) & kRadixMask; } + bool compare(const T& x, const T& y) { return x < y; } +}; + +template +struct RadixTraitsSigned +{ + static const int nBytes = sizeof(T); + static const T kMSB = T(0x80) << ((sizeof(T) - 1) * 8); + int kth_byte(const T& x, int k) { return ((x ^ kMSB) >> (kRadixBits * k)) & kRadixMask; } + bool compare(const T& x, const T& y) { return x < y; } +}; + +template +inline void insert_sort_core_(RandomIt s, RandomIt e, RadixTraits radix_traits) +{ + for (RandomIt i = s + 1; i < e; ++i) + { + if (radix_traits.compare(*i, *(i - 1))) + { + RandomIt j; + ValueType tmp = *i; + *i = *(i - 1); + for (j = i - 1; j > s && radix_traits.compare(tmp, *(j - 1)); --j) + { + *j = *(j - 1); + } + *j = tmp; + } + } +} + +template +inline void radix_sort_core_(RandomIt s, RandomIt e, RadixTraits radix_traits) +{ + RandomIt last_[kRadixBin + 1]; + RandomIt* last = last_ + 1; + size_t count[kRadixBin] = { 0 }; + + for (RandomIt i = s; i < e; ++i) + { + ++count[radix_traits.kth_byte(*i, kWhichByte)]; + } + + last_[0] = last_[1] = s; + + for (int i = 1; i < kRadixBin; ++i) + { + last[i] = last[i - 1] + count[i - 1]; + } + + for (int i = 0; i < kRadixBin; ++i) + { + RandomIt end = last[i - 1] + count[i]; + if (end == e) + { + last[i] = e; + break; + } + while (last[i] != end) + { + ValueType swapper = *last[i]; + int tag = radix_traits.kth_byte(swapper, kWhichByte); + if (tag != i) + { + do + { + std::swap(swapper, *last[tag]++); + } while ((tag = radix_traits.kth_byte(swapper, kWhichByte)) != i); + *last[i] = swapper; + } + ++last[i]; + } + } + + if (kWhichByte > 0) + { + for (int i = 0; i < kRadixBin; ++i) + { + if (count[i] > kInsertSortThreshold) + { + radix_sort_core_ 0 ? (kWhichByte - 1) : 0)>( + last[i - 1], last[i], radix_traits); + } + else if (count[i] > 1) + { + insert_sort_core_(last[i - 1], last[i], radix_traits); + } + } + } +} + +template +inline void radix_sort_entry_(RandomIt s, RandomIt e, ValueType*, RadixTraits radix_traits) +{ + if (e - s <= (int)kInsertSortThreshold) + insert_sort_core_(s, e, radix_traits); + else + radix_sort_core_(s, e, radix_traits); +} + +template +inline void radix_sort_entry_(RandomIt s, RandomIt e, ValueType*) +{ + if (ValueType(-1) > ValueType(0)) + { + radix_sort_entry_(s, e, (ValueType*)(0), RadixTraitsUnsigned()); + } + else + { + radix_sort_entry_(s, e, (ValueType*)(0), RadixTraitsSigned()); + } +} + +//================= INTERFACES ==================== + +template +inline void radix_sort(RandomIt s, RandomIt e, RadixTraits radix_traits) +{ + typename std::iterator_traits::value_type* dummy(0); + radix_sort_entry_(s, e, dummy, radix_traits); +} + +template +inline void radix_sort(RandomIt s, RandomIt e) +{ + typename std::iterator_traits::value_type* dummy(0); + radix_sort_entry_(s, e, dummy); +} +} + +#endif diff --git a/vtkm/cont/tbb/testing/CMakeLists.txt b/vtkm/cont/tbb/testing/CMakeLists.txt index 246acfc35..470172fdd 100644 --- a/vtkm/cont/tbb/testing/CMakeLists.txt +++ b/vtkm/cont/tbb/testing/CMakeLists.txt @@ -31,4 +31,5 @@ set(unit_tests UnitTestTBBPointLocatorUniformGrid.cxx UnitTestTBBVirtualObjectHandle.cxx ) + vtkm_unit_tests(SOURCES ${unit_tests} BACKEND TBB) diff --git a/vtkm/cont/testing/TestingCellLocatorTwoLevelUniformGrid.h b/vtkm/cont/testing/TestingCellLocatorTwoLevelUniformGrid.h index 87616ef97..11fd55fb9 100644 --- a/vtkm/cont/testing/TestingCellLocatorTwoLevelUniformGrid.h +++ b/vtkm/cont/testing/TestingCellLocatorTwoLevelUniformGrid.h @@ -128,7 +128,7 @@ vtkm::cont::DataSet MakeTestDataSet(const vtkm::Vec& dims, VTKM_ASSERT(false); } - // It is posible that the warping will result in invalid cells. So use a + // It is possible that the warping will result in invalid cells. So use a // local random generator with a known seed that does not create invalid cells. std::default_random_engine rgen; diff --git a/vtkm/cont/testing/TestingDeviceAdapter.h b/vtkm/cont/testing/TestingDeviceAdapter.h index dffdb96f1..53aa22f18 100644 --- a/vtkm/cont/testing/TestingDeviceAdapter.h +++ b/vtkm/cont/testing/TestingDeviceAdapter.h @@ -1070,7 +1070,6 @@ private: std::cout << " Reduce with 0 values." << std::endl; array.Shrink(0); vtkm::Id reduce_sum_no_values = Algorithm::Reduce(array, vtkm::Id(0)); - VTKM_TEST_ASSERT(reduce_sum == OFFSET * ARRAY_SIZE, "Got bad sum from Reduce"); VTKM_TEST_ASSERT(reduce_sum_with_intial_value == reduce_sum + ARRAY_SIZE, "Got bad sum from Reduce with initial value"); diff --git a/vtkm/cont/testing/TestingPointLocatorUniformGrid.h b/vtkm/cont/testing/TestingPointLocatorUniformGrid.h index 7a2c9fe59..77a38ba3a 100644 --- a/vtkm/cont/testing/TestingPointLocatorUniformGrid.h +++ b/vtkm/cont/testing/TestingPointLocatorUniformGrid.h @@ -79,7 +79,7 @@ template class TestingPointLocatorUniformGrid { public: - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; void TestTest() const { vtkm::Int32 nTrainingPoints = 1000; diff --git a/vtkm/cont/testing/UnitTestDeviceAdapterAlgorithmGeneral.cxx b/vtkm/cont/testing/UnitTestDeviceAdapterAlgorithmGeneral.cxx index 8aac3de04..89cd3f492 100644 --- a/vtkm/cont/testing/UnitTestDeviceAdapterAlgorithmGeneral.cxx +++ b/vtkm/cont/testing/UnitTestDeviceAdapterAlgorithmGeneral.cxx @@ -126,7 +126,7 @@ struct ExecutionArrayInterfaceBasic } VTKM_CONT - virtual DeviceAdapterId GetDeviceId() const final { return -3; } + DeviceAdapterId GetDeviceId() const final { return -3; } }; } } diff --git a/vtkm/cont/testing/UnitTestStorageBasic.cxx b/vtkm/cont/testing/UnitTestStorageBasic.cxx index 6e89783e9..2f754f0e8 100644 --- a/vtkm/cont/testing/UnitTestStorageBasic.cxx +++ b/vtkm/cont/testing/UnitTestStorageBasic.cxx @@ -26,16 +26,6 @@ #include #include -// We use these to check if the aligned allocator provided by -// StorageBasic can be used with all STL containers -#include -#include -#include -#include -#include -#include -#include - namespace { @@ -72,53 +62,6 @@ struct TemplatedTests typename vtkm::VecTraits::ComponentType STOLEN_ARRAY_VALUE() { return 29; } - void TestAlignedAllocatorSTL() - { - using Allocator = typename StorageType::AllocatorType; - std::vector vec(ARRAY_SIZE, ValueType()); - StorageType store(&vec[0], ARRAY_SIZE); - } - - // This test checks that we can compile and use the allocator with all - // STL containers - void CompileSTLAllocator() - { - using Allocator = typename StorageType::AllocatorType; - using PairAllocator = - typename StorageType::AllocatorType::template rebind>::other; - std::vector v; - ValueType value = vtkm::TypeTraits::ZeroInitialization(); - - v.push_back(value); - - std::deque d; - d.push_front(value); - - std::list l; - l.push_front(value); - - std::set, Allocator> set; - set.insert(value); - - std::map, PairAllocator> m; - m[value] = value; - - std::multiset, Allocator> ms; - ms.insert(value); - - std::multimap, PairAllocator> mm; - mm.insert(std::pair(value, value)); - - std::stack> stack; - stack.push(value); - - std::queue> queue; - queue.push(value); - - std::priority_queue> pqueue; - pqueue.push(value); - } - /// Returned value should later be passed to StealArray2. It is best to /// put as much between the two test parts to maximize the chance of a /// deallocated array being overridden (and thus detected). @@ -153,7 +96,7 @@ struct TemplatedTests "Stolen array did not retain values."); } typename StorageType::AllocatorType allocator; - allocator.deallocate(stolenArray, ARRAY_SIZE); + allocator.deallocate(stolenArray); } void BasicAllocation() @@ -199,9 +142,6 @@ struct TemplatedTests BasicAllocation(); StealArray2(stolenArray); - - TestAlignedAllocatorSTL(); - CompileSTLAllocator(); } }; diff --git a/vtkm/exec/CMakeLists.txt b/vtkm/exec/CMakeLists.txt index 434d51370..5ade2feea 100644 --- a/vtkm/exec/CMakeLists.txt +++ b/vtkm/exec/CMakeLists.txt @@ -31,7 +31,6 @@ set(headers ExecutionObjectBase.h ExecutionWholeArray.h FunctorBase.h - ImplicitFunction.h Jacobian.h ParametricCoordinates.h TaskBase.h diff --git a/vtkm/exec/CellDerivative.h b/vtkm/exec/CellDerivative.h index f90d96439..1560ce71f 100644 --- a/vtkm/exec/CellDerivative.h +++ b/vtkm/exec/CellDerivative.h @@ -45,9 +45,9 @@ namespace exec namespace { #define VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(pointIndex, weight0, weight1, weight2) \ - parametricDerivative[0] += field[pointIndex] * weight0; \ - parametricDerivative[1] += field[pointIndex] * weight1; \ - parametricDerivative[2] += field[pointIndex] * weight2 + parametricDerivative[0] += field[pointIndex] * (weight0); \ + parametricDerivative[1] += field[pointIndex] * (weight1); \ + parametricDerivative[2] += field[pointIndex] * (weight2) // Find the derivative of a field in parametric space. That is, find the // vector [ds/du, ds/dv, ds/dw]. @@ -64,14 +64,7 @@ VTKM_EXEC vtkm::Vec ParametricDerivativ GradientType rc = GradientType(FieldType(1)) - pc; GradientType parametricDerivative(FieldType(0)); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(0, -rc[1] * rc[2], -rc[0] * rc[2], -rc[0] * rc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(1, rc[1] * rc[2], -pc[0] * rc[2], -pc[0] * rc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(2, pc[1] * rc[2], pc[0] * rc[2], -pc[0] * pc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(3, -pc[1] * rc[2], rc[0] * rc[2], -rc[0] * pc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(4, -rc[1] * pc[2], -rc[0] * pc[2], rc[0] * rc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(5, rc[1] * pc[2], -pc[0] * pc[2], pc[0] * rc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(6, pc[1] * pc[2], pc[0] * pc[2], pc[0] * pc[1]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D(7, -pc[1] * pc[2], rc[0] * pc[2], rc[0] * pc[1]); + VTKM_DERIVATIVE_WEIGHTS_HEXAHEDRON(pc, rc, VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D); return parametricDerivative; } @@ -81,22 +74,16 @@ VTKM_EXEC vtkm::Vec ParametricDerivativ const vtkm::Vec& pcoords, vtkm::CellShapeTagWedge) { -#if 0 - // This is not working. Just leverage the hexahedron code that is working. using FieldType = typename FieldVecType::ComponentType; - using GradientType = vtkm::Vec; + using GradientType = vtkm::Vec; GradientType pc(pcoords); - GradientType rc = GradientType(1) - pc; + GradientType rc = GradientType(FieldType(1)) - pc; - GradientType parametricDerivative(0); + GradientType parametricDerivative(FieldType(0)); VTKM_DERIVATIVE_WEIGHTS_WEDGE(pc, rc, VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D); return parametricDerivative; -#else - return ParametricDerivative( - vtkm::exec::internal::PermuteWedgeToHex(field), pcoords, vtkm::CellShapeTagHexahedron()); -#endif } template @@ -105,29 +92,23 @@ VTKM_EXEC vtkm::Vec ParametricDerivativ const vtkm::Vec& pcoords, vtkm::CellShapeTagPyramid) { -#if 0 - // This is not working. Just leverage the hexahedron code that is working. using FieldType = typename FieldVecType::ComponentType; - using GradientType = vtkm::Vec; + using GradientType = vtkm::Vec; GradientType pc(pcoords); - GradientType rc = GradientType(1) - pc; + GradientType rc = GradientType(FieldType(1)) - pc; - GradientType parametricDerivative(0); + GradientType parametricDerivative(FieldType(0)); VTKM_DERIVATIVE_WEIGHTS_PYRAMID(pc, rc, VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D); return parametricDerivative; -#else - return ParametricDerivative( - vtkm::exec::internal::PermutePyramidToHex(field), pcoords, vtkm::CellShapeTagHexahedron()); -#endif } #undef VTKM_ACCUM_PARAMETRIC_DERIVATIVE_3D #define VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D(pointIndex, weight0, weight1) \ - parametricDerivative[0] += field[pointIndex] * weight0; \ - parametricDerivative[1] += field[pointIndex] * weight1 + parametricDerivative[0] += field[pointIndex] * (weight0); \ + parametricDerivative[1] += field[pointIndex] * (weight1) template VTKM_EXEC vtkm::Vec ParametricDerivative( @@ -142,10 +123,7 @@ VTKM_EXEC vtkm::Vec ParametricDerivativ GradientType rc = GradientType(FieldType(1)) - pc; GradientType parametricDerivative(FieldType(0)); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D(0, -rc[1], -rc[0]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D(1, rc[1], -pc[0]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D(2, pc[1], pc[0]); - VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D(3, -pc[1], rc[0]); + VTKM_DERIVATIVE_WEIGHTS_QUAD(pc, rc, VTKM_ACCUM_PARAMETRIC_DERIVATIVE_2D); return parametricDerivative; } diff --git a/vtkm/exec/CellFace.h b/vtkm/exec/CellFace.h index 161f97272..1ee78c6e4 100644 --- a/vtkm/exec/CellFace.h +++ b/vtkm/exec/CellFace.h @@ -265,7 +265,7 @@ static inline VTKM_EXEC vtkm::VecCConst CellFaceLocalIndices( numPointsInFace); } -/// \brief Returns a canonical identifer for a cell face +/// \brief Returns a canonical identifier for a cell face /// /// Given information about a cell face and the global point indices for that cell, returns a /// vtkm::Id3 that contains values that are unique to that face. The values for two faces will be diff --git a/vtkm/exec/CellInterpolate.h b/vtkm/exec/CellInterpolate.h index a105463ae..c296c4f69 100644 --- a/vtkm/exec/CellInterpolate.h +++ b/vtkm/exec/CellInterpolate.h @@ -67,8 +67,8 @@ VTKM_EXEC typename WorldCoordVector::ComponentType ReverseInterpolateTriangle( // // In this diagram, the distance between p0 and the point marked x divided by // the length of the edge it is on is equal, by proportionality, to the u - // parametric coordiante. (The v coordinate follows the other edge - // accordingly.) Thus, if we can find the interesection at x (or more + // parametric coordinate. (The v coordinate follows the other edge + // accordingly.) Thus, if we can find the intersection at x (or more // specifically the distance between p0 and x), then we can find that // parametric coordinate. // @@ -94,13 +94,13 @@ VTKM_EXEC typename WorldCoordVector::ComponentType ReverseInterpolateTriangle( // compute it, we are done. We can skip the part about finding the actual // coordinates of the intersection. // - // Solving for the interesection is as simple as substituting the line's + // Solving for the intersection is as simple as substituting the line's // definition of p(d) into p for the plane equation. With some basic algebra // you get: // // d = dot((wcoords - p0), planeNormal)/dot((p1-p0), planeNormal) // - // From here, the u coordiante is simply d. The v coordinate follows + // From here, the u coordinate is simply d. The v coordinate follows // similarly. // diff --git a/vtkm/exec/ImplicitFunction.h b/vtkm/exec/ImplicitFunction.h deleted file mode 100644 index a08945f86..000000000 --- a/vtkm/exec/ImplicitFunction.h +++ /dev/null @@ -1,145 +0,0 @@ -//============================================================================ -// Copyright (c) Kitware, Inc. -// All rights reserved. -// See LICENSE.txt for details. -// This software is distributed WITHOUT ANY WARRANTY; without even -// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -// PURPOSE. See the above copyright notice for more information. -// -// Copyright 2017 National Technology & Engineering Solutions of Sandia, LLC (NTESS). -// Copyright 2017 UT-Battelle, LLC. -// Copyright 2017 Los Alamos National Security. -// -// Under the terms of Contract DE-NA0003525 with NTESS, -// the U.S. Government retains certain rights in this software. -// -// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National -// Laboratory (LANL), the U.S. Government retains certain rights in -// this software. -//============================================================================ -#ifndef vtk_m_exec_ImplicitFunction_h -#define vtk_m_exec_ImplicitFunction_h - -#include - -namespace vtkm -{ -namespace exec -{ - -class VTKM_ALWAYS_EXPORT ImplicitFunction -{ -public: - ImplicitFunction() - : Function(nullptr) - , ValueCaller(nullptr) - , GradientCaller(nullptr) - { - } - - VTKM_EXEC - FloatDefault Value(FloatDefault x, FloatDefault y, FloatDefault z) const - { - return this->ValueCaller(this->Function, x, y, z); - } - - VTKM_EXEC - FloatDefault Value(const vtkm::Vec& x) const - { - return this->ValueCaller(this->Function, x[0], x[1], x[2]); - } - - VTKM_EXEC - vtkm::Vec Gradient(FloatDefault x, FloatDefault y, FloatDefault z) const - { - return this->GradientCaller(this->Function, x, y, z); - } - - VTKM_EXEC - vtkm::Vec Gradient(const vtkm::Vec& x) const - { - return this->GradientCaller(this->Function, x[0], x[1], x[2]); - } - - template - VTKM_EXEC void Bind(const T* function) - { - this->Function = function; - this->ValueCaller = [](const void* t, FloatDefault x, FloatDefault y, FloatDefault z) { - return static_cast(t)->Value(x, y, z); - }; - this->GradientCaller = [](const void* t, FloatDefault x, FloatDefault y, FloatDefault z) { - return static_cast(t)->Gradient(x, y, z); - }; - } - -private: - using ValueCallerSig = FloatDefault(const void*, FloatDefault, FloatDefault, FloatDefault); - using GradientCallerSig = vtkm::Vec(const void*, - FloatDefault, - FloatDefault, - FloatDefault); - - const void* Function; - ValueCallerSig* ValueCaller; - GradientCallerSig* GradientCaller; -}; - -/// \brief A function object that evaluates the contained implicit function -class VTKM_ALWAYS_EXPORT ImplicitFunctionValue -{ -public: - ImplicitFunctionValue() = default; - - explicit ImplicitFunctionValue(const vtkm::exec::ImplicitFunction& func) - : Function(func) - { - } - - VTKM_EXEC - FloatDefault operator()(const vtkm::Vec x) const - { - return this->Function.Value(x); - } - - VTKM_EXEC - FloatDefault operator()(FloatDefault x, FloatDefault y, FloatDefault z) const - { - return this->Function.Value(x, y, z); - } - -private: - vtkm::exec::ImplicitFunction Function; -}; - -/// \brief A function object that computes the gradient of the contained implicit -/// function and the specified point. -class VTKM_ALWAYS_EXPORT ImplicitFunctionGradient -{ -public: - ImplicitFunctionGradient() = default; - - explicit ImplicitFunctionGradient(const vtkm::exec::ImplicitFunction& func) - : Function(func) - { - } - - VTKM_EXEC - vtkm::Vec operator()(const vtkm::Vec x) const - { - return this->Function.Gradient(x); - } - - VTKM_EXEC - vtkm::Vec operator()(FloatDefault x, FloatDefault y, FloatDefault z) const - { - return this->Function.Gradient(x, y, z); - } - -private: - vtkm::exec::ImplicitFunction Function; -}; -} -} // vtkm::exec - -#endif // vtk_m_exec_ImplicitFunction_h diff --git a/vtkm/exec/Jacobian.h b/vtkm/exec/Jacobian.h index 027245378..d4de228c9 100644 --- a/vtkm/exec/Jacobian.h +++ b/vtkm/exec/Jacobian.h @@ -68,98 +68,38 @@ struct Space2D } }; -// Given a series of point values for a wedge, return a new series of point -// for a hexahedron that has the same interpolation within the wedge. -template -VTKM_EXEC vtkm::Vec PermuteWedgeToHex( - const FieldVecType& field) -{ - vtkm::Vec hexField; - - hexField[0] = field[0]; - hexField[1] = field[2]; - hexField[2] = field[2] + field[1] - field[0]; - hexField[3] = field[1]; - hexField[4] = field[3]; - hexField[5] = field[5]; - hexField[6] = field[5] + field[4] - field[3]; - hexField[7] = field[4]; - - return hexField; -} - -// Given a series of point values for a pyramid, return a new series of point -// for a hexahedron that has the same interpolation within the pyramid. -template -VTKM_EXEC vtkm::Vec PermutePyramidToHex( - const FieldVecType& field) -{ - using T = typename FieldVecType::ComponentType; - - vtkm::Vec hexField; - - T baseCenter = T(0.25f) * (field[0] + field[1] + field[2] + field[3]); - - hexField[0] = field[0]; - hexField[1] = field[1]; - hexField[2] = field[2]; - hexField[3] = field[3]; - hexField[4] = field[4] + (field[0] - baseCenter); - hexField[5] = field[4] + (field[1] - baseCenter); - hexField[6] = field[4] + (field[2] - baseCenter); - hexField[7] = field[4] + (field[3] - baseCenter); - - return hexField; -} - } //namespace internal #define VTKM_DERIVATIVE_WEIGHTS_HEXAHEDRON(pc, rc, call) \ - call(0, -rc[1] * rc[2], -rc[0] * rc[2], -rc[0] * rc[1]); \ - call(1, rc[1] * rc[2], -pc[0] * rc[2], -pc[0] * rc[1]); \ - call(2, pc[1] * rc[2], pc[0] * rc[2], -pc[0] * pc[1]); \ - call(3, -pc[1] * rc[2], rc[0] * rc[2], -rc[0] * pc[1]); \ - call(4, -rc[1] * pc[2], -rc[0] * pc[2], rc[0] * rc[1]); \ - call(5, rc[1] * pc[2], -pc[0] * pc[2], pc[0] * rc[1]); \ - call(6, pc[1] * pc[2], pc[0] * pc[2], pc[0] * pc[1]); \ - call(7, -pc[1] * pc[2], rc[0] * pc[2], rc[0] * pc[1]) - -#define VTKM_DERIVATIVE_WEIGHTS_VOXEL(pc, rc, call) \ - call(0, -rc[1] * rc[2], -rc[0] * rc[2], -rc[0] * rc[1]); \ - call(1, rc[1] * rc[2], -pc[0] * rc[2], -pc[0] * rc[1]); \ - call(2, -pc[1] * rc[2], rc[0] * rc[2], -rc[0] * pc[1]); \ - call(3, pc[1] * rc[2], pc[0] * rc[2], -pc[0] * pc[1]); \ - call(4, -rc[1] * pc[2], -rc[0] * pc[2], rc[0] * rc[1]); \ - call(5, rc[1] * pc[2], -pc[0] * pc[2], pc[0] * rc[1]); \ - call(6, -pc[1] * pc[2], rc[0] * pc[2], rc[0] * pc[1]); \ - call(7, pc[1] * pc[2], pc[0] * pc[2], pc[0] * pc[1]) + call(0, (-rc[1] * rc[2]), (-rc[0] * rc[2]), (-rc[0] * rc[1])); \ + call(1, (rc[1] * rc[2]), (-pc[0] * rc[2]), (-pc[0] * rc[1])); \ + call(2, (pc[1] * rc[2]), (pc[0] * rc[2]), (-pc[0] * pc[1])); \ + call(3, (-pc[1] * rc[2]), (rc[0] * rc[2]), (-rc[0] * pc[1])); \ + call(4, (-rc[1] * pc[2]), (-rc[0] * pc[2]), (rc[0] * rc[1])); \ + call(5, (rc[1] * pc[2]), (-pc[0] * pc[2]), (pc[0] * rc[1])); \ + call(6, (pc[1] * pc[2]), (pc[0] * pc[2]), (pc[0] * pc[1])); \ + call(7, (-pc[1] * pc[2]), (rc[0] * pc[2]), (rc[0] * pc[1])) #define VTKM_DERIVATIVE_WEIGHTS_WEDGE(pc, rc, call) \ - call(0, -rc[2], -rc[2], -1.0f + pc[0] + pc[1]); \ - call(1, 0.0f, rc[2], -pc[1]); \ - call(2, rc[2], 0.0f, -pc[0]); \ - call(3, -pc[2], -pc[2], 1.0f - pc[0] - pc[1]); \ - call(4, 0.0f, pc[2], pc[1]); \ - call(5, pc[2], 0.0f, pc[0]) + call(0, (-rc[2]), (-rc[2]), (pc[0] - rc[1])); \ + call(1, (0.0f), (rc[2]), (-pc[1])); \ + call(2, (rc[2]), (0.0f), (-pc[0])); \ + call(3, (-pc[2]), (-pc[2]), (rc[0] - pc[1])); \ + call(4, (0.0f), (pc[2]), (pc[1])); \ + call(5, (pc[2]), (0.0f), (pc[0])) #define VTKM_DERIVATIVE_WEIGHTS_PYRAMID(pc, rc, call) \ - call(0, -rc[1] * rc[2], -rc[0] * rc[2], -rc[0] * rc[1]); \ - call(1, rc[1] * rc[2], -pc[0] * rc[2], -pc[0] * rc[1]); \ - call(2, pc[1] * rc[2], pc[0] * rc[2], -pc[0] * pc[1]); \ - call(3, -pc[1] * rc[2], rc[0] * rc[2], -rc[0] * pc[1]); \ - call(3, 0.0f, 0.0f, 1.0f) + call(0, (-rc[1] * rc[2]), (-rc[0] * rc[2]), (-rc[0] * rc[1])); \ + call(1, (rc[1] * rc[2]), (-pc[0] * rc[2]), (-pc[0] * rc[1])); \ + call(2, (pc[1] * rc[2]), (pc[0] * rc[2]), (-pc[0] * pc[1])); \ + call(3, (-pc[1] * rc[2]), (rc[0] * rc[2]), (-rc[0] * pc[1])); \ + call(4, (0.0f), (0.0f), (1.0f)) #define VTKM_DERIVATIVE_WEIGHTS_QUAD(pc, rc, call) \ - call(0, -rc[1], -rc[0]); \ - call(1, rc[1], -pc[0]); \ - call(2, pc[1], pc[0]); \ - call(3, -pc[1], rc[0]) - -#define VTKM_DERIVATIVE_WEIGHTS_PIXEL(pc, rc, call) \ - call(0, -rc[1], -rc[0]); \ - call(1, rc[1], -pc[0]); \ - call(2, -pc[1], rc[0]); \ - call(3, pc[1], pc[0]) + call(0, (-rc[1]), (-rc[0])); \ + call(1, (rc[1]), (-pc[0])); \ + call(2, (pc[1]), (pc[0])); \ + call(3, (-pc[1]), (rc[0])) //----------------------------------------------------------------------------- // This returns the Jacobian of a hexahedron's (or other 3D cell's) coordinates @@ -205,17 +145,11 @@ VTKM_EXEC void JacobianFor3DCell(const WorldCoordType& wCoords, vtkm::Matrix& jacobian, vtkm::CellShapeTagWedge) { -#if 0 - // This is not working. Just leverage the hexahedron code that is working. - vtkm::Vec pc(pcoords); - vtkm::Vec rc = vtkm::Vec(1) - pc; + vtkm::Vec pc(pcoords); + vtkm::Vec rc = vtkm::Vec(JacobianType(1)) - pc; - jacobian = vtkm::Matrix(0); + jacobian = vtkm::Matrix(JacobianType(0)); VTKM_DERIVATIVE_WEIGHTS_WEDGE(pc, rc, VTKM_ACCUM_JACOBIAN_3D); -#else - JacobianFor3DCell( - internal::PermuteWedgeToHex(wCoords), pcoords, jacobian, vtkm::CellShapeTagHexahedron()); -#endif } template @@ -224,17 +158,11 @@ VTKM_EXEC void JacobianFor3DCell(const WorldCoordType& wCoords, vtkm::Matrix& jacobian, vtkm::CellShapeTagPyramid) { -#if 0 - // This is not working. Just leverage the hexahedron code that is working. - vtkm::Vec pc(pcoords); - vtkm::Vec rc = vtkm::Vec(1) - pc; + vtkm::Vec pc(pcoords); + vtkm::Vec rc = vtkm::Vec(JacobianType(1)) - pc; - jacobian = vtkm::Matrix(0); + jacobian = vtkm::Matrix(JacobianType(0)); VTKM_DERIVATIVE_WEIGHTS_PYRAMID(pc, rc, VTKM_ACCUM_JACOBIAN_3D); -#else - JacobianFor3DCell( - internal::PermutePyramidToHex(wCoords), pcoords, jacobian, vtkm::CellShapeTagHexahedron()); -#endif } // Derivatives in quadrilaterals are computed in much the same way as @@ -316,13 +244,6 @@ void JacobianFor2DCell(const WorldCoordType &wCoords, #undef VTKM_ACCUM_JACOBIAN_3D #undef VTKM_ACCUM_JACOBIAN_2D - -#undef VTKM_DERIVATIVE_WEIGHTS_HEXAHEDRON -#undef VTKM_DERIVATIVE_WEIGHTS_VOXEL -#undef VTKM_DERIVATIVE_WEIGHTS_WEDGE -#undef VTKM_DERIVATIVE_WEIGHTS_PYRAMID -#undef VTKM_DERIVATIVE_WEIGHTS_QUAD -#undef VTKM_DERIVATIVE_WEIGHTS_PIXEL } } // namespace vtkm::exec #endif //vtk_m_exec_Jacobian_h diff --git a/vtkm/exec/ParametricCoordinates.h b/vtkm/exec/ParametricCoordinates.h index 9bf5f0361..e1e683e26 100644 --- a/vtkm/exec/ParametricCoordinates.h +++ b/vtkm/exec/ParametricCoordinates.h @@ -28,6 +28,7 @@ #include #include #include +#include #include namespace vtkm @@ -586,7 +587,77 @@ ParametricCoordinatesToWorldCoordinates(const WorldCoordVector& pointWCoords, } //----------------------------------------------------------------------------- +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector&, + const typename WorldCoordVector::ComponentType&, + vtkm::CellShapeTagEmpty, + bool& success, + const vtkm::exec::FunctorBase& worklet) +{ + worklet.RaiseError("Attempted to find point coordinates in empty cell."); + success = false; + return typename WorldCoordVector::ComponentType(); +} +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType&, + vtkm::CellShapeTagVertex, + bool& success, + const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) +{ + (void)pointWCoords; // Silence compiler warnings. + VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 1); + success = true; + return typename WorldCoordVector::ComponentType(0, 0, 0); +} + +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + vtkm::CellShapeTagLine, + bool& success, + const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) +{ + VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 2); + success = true; + + // Because this is a line, there is only one valid parametric coordinate. Let + // vec be the vector from the first point to the second point + // (pointWCoords[1] - pointWCoords[0]), which is the direction of the line. + // dot(vec,wcoords-pointWCoords[0])/mag(vec) is the orthoginal projection of + // wcoords on the line and represents the distance between the orthoginal + // projection and pointWCoords[0]. The parametric coordinate is the fraction + // of this over the length of the segment, which is mag(vec). Thus, the + // parametric coordinate is dot(vec,wcoords-pointWCoords[0])/mag(vec)^2. + + using Vector3 = typename WorldCoordVector::ComponentType; + using T = typename Vector3::ComponentType; + + Vector3 vec = pointWCoords[1] - pointWCoords[0]; + T numerator = vtkm::dot(vec, wcoords - pointWCoords[0]); + T denominator = vtkm::MagnitudeSquared(vec); + + return Vector3(numerator / denominator, 0, 0); +} + +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + vtkm::CellShapeTagTriangle, + bool& success, + const vtkm::exec::FunctorBase&) +{ + success = true; + vtkm::exec::internal::FastVec local(pointWCoords); + return vtkm::exec::internal::ReverseInterpolateTriangle(local.Get(), wcoords); +} + +//----------------------------------------------------------------------------- namespace detail { @@ -655,160 +726,37 @@ public: } }; -template -class JacobianFunctor3DCell -{ - using T = typename WorldCoordVector::ComponentType::ComponentType; - using Vector3 = vtkm::Vec; - using Matrix3x3 = vtkm::Matrix; - - const WorldCoordVector* PointWCoords; - -public: - VTKM_EXEC - JacobianFunctor3DCell(const WorldCoordVector* pointWCoords) - : PointWCoords(pointWCoords) - { - } - - VTKM_EXEC - Matrix3x3 operator()(const Vector3& pcoords) const - { - Matrix3x3 jacobian; - vtkm::exec::JacobianFor3DCell(*this->PointWCoords, pcoords, jacobian, CellShapeTag()); - return jacobian; - } -}; - -template -class CoordinatesFunctor3DCell -{ - using T = typename WorldCoordVector::ComponentType::ComponentType; - using Vector3 = vtkm::Vec; - - const WorldCoordVector* PointWCoords; - const vtkm::exec::FunctorBase* Worklet; - -public: - VTKM_EXEC - CoordinatesFunctor3DCell(const WorldCoordVector* pointWCoords, - const vtkm::exec::FunctorBase* worklet) - : PointWCoords(pointWCoords) - , Worklet(worklet) - { - } - - VTKM_EXEC - Vector3 operator()(Vector3 pcoords) const - { - return vtkm::exec::ParametricCoordinatesToWorldCoordinates( - *this->PointWCoords, pcoords, CellShapeTag(), *this->Worklet); - } -}; - -template +template static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates3D(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType& wcoords, - CellShapeTag, - bool& success, - const vtkm::exec::FunctorBase& worklet) +WorldCoordinatesToParametricCoordinatesQuad(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + bool& success, + const vtkm::exec::FunctorBase& worklet) { - auto result = vtkm::NewtonsMethod( - JacobianFunctor3DCell(&pointWCoords), - CoordinatesFunctor3DCell(&pointWCoords, &worklet), - wcoords, - typename WorldCoordVector::ComponentType(0.5f, 0.5f, 0.5f)); - success = result.Valid; - return result.Solution; -} + using T = typename WorldCoordVector::ComponentType::ComponentType; + using Vector2 = vtkm::Vec; + using Vector3 = vtkm::Vec; + // We have an underdetermined system in 3D, so create a 2D space in the + // plane that the polygon sits. + vtkm::exec::internal::Space2D space(pointWCoords[0], pointWCoords[1], pointWCoords[3]); + + auto result = vtkm::NewtonsMethod( + JacobianFunctorQuad(&pointWCoords, &space), + CoordinatesFunctorQuad( + &pointWCoords, &space, &worklet), + space.ConvertCoordToSpace(wcoords), + Vector2(0.5f, 0.5f)); + + success = result.Valid; + return Vector3(result.Solution[0], result.Solution[1], 0); +} } // namespace detail -//----------------------------------------------------------------------------- -template -static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagGeneric shape, - bool& success, - const vtkm::exec::FunctorBase& worklet) -{ - typename WorldCoordVector::ComponentType result; - switch (shape.Id) - { - vtkmGenericCellShapeMacro(result = WorldCoordinatesToParametricCoordinates( - pointWCoords, wcoords, CellShapeTag(), success, worklet)); - default: - success = false; - worklet.RaiseError("Unknown cell shape sent to world 2 parametric."); - return typename WorldCoordVector::ComponentType(); - } - - return result; -} - -template -static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector&, - const typename WorldCoordVector::ComponentType&, - vtkm::CellShapeTagEmpty, - bool& success, - const vtkm::exec::FunctorBase& worklet) -{ - worklet.RaiseError("Attempted to find point coordinates in empty cell."); - success = false; - return typename WorldCoordVector::ComponentType(); -} - -template -static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType&, - vtkm::CellShapeTagVertex, - bool& success, - const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) -{ - (void)pointWCoords; // Silence compiler warnings. - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 1); - success = true; - return typename WorldCoordVector::ComponentType(0, 0, 0); -} - -template -static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagLine, - bool& success, - const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) -{ - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 2); - success = true; - - // Because this is a line, there is only one vaild parametric coordinate. Let - // vec be the vector from the first point to the second point - // (pointWCoords[1] - pointWCoords[0]), which is the direction of the line. - // dot(vec,wcoords-pointWCoords[0])/mag(vec) is the orthoginal projection of - // wcoords on the line and represents the distance between the orthoginal - // projection and pointWCoords[0]. The parametric coordinate is the fraction - // of this over the length of the segment, which is mag(vec). Thus, the - // parametric coordinate is dot(vec,wcoords-pointWCoords[0])/mag(vec)^2. - - using Vector3 = typename WorldCoordVector::ComponentType; - using T = typename Vector3::ComponentType; - - Vector3 vec = pointWCoords[1] - pointWCoords[0]; - T numerator = vtkm::dot(vec, wcoords - pointWCoords[0]); - T denominator = vtkm::MagnitudeSquared(vec); - - return Vector3(numerator / denominator, 0, 0); -} - static inline VTKM_EXEC vtkm::Vec WorldCoordinatesToParametricCoordinates( - const vtkm::VecAxisAlignedPointCoordinates<1>& pointWCoords, + const vtkm::VecAxisAlignedPointCoordinates<2>& pointWCoords, const vtkm::Vec& wcoords, - vtkm::CellShapeTagLine, + vtkm::CellShapeTagQuad, bool& success, const FunctorBase&) { @@ -820,14 +768,16 @@ template static inline VTKM_EXEC typename WorldCoordVector::ComponentType WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagTriangle, + vtkm::CellShapeTagQuad, bool& success, - const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) + const vtkm::exec::FunctorBase& worklet) { - success = true; - return vtkm::exec::internal::ReverseInterpolateTriangle(pointWCoords, wcoords); + vtkm::exec::internal::FastVec local(pointWCoords); + return detail::WorldCoordinatesToParametricCoordinatesQuad( + local.Get(), wcoords, success, worklet); } +//----------------------------------------------------------------------------- template static inline VTKM_EXEC typename WorldCoordVector::ComponentType WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, @@ -951,57 +901,16 @@ WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, triangleWCoords, trianglePCoords, vtkm::CellShapeTagTriangle(), worklet); } -template -static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagQuad, - bool& success, - const vtkm::exec::FunctorBase& worklet) +//----------------------------------------------------------------------------- +namespace detail { - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 4); - - using T = typename WorldCoordVector::ComponentType::ComponentType; - using Vector2 = vtkm::Vec; - using Vector3 = vtkm::Vec; - - // We have an underdetermined system in 3D, so create a 2D space in the - // plane that the polygon sits. - vtkm::exec::internal::Space2D space(pointWCoords[0], pointWCoords[1], pointWCoords[3]); - - auto result = vtkm::NewtonsMethod( - detail::JacobianFunctorQuad(&pointWCoords, &space), - detail::CoordinatesFunctorQuad( - &pointWCoords, &space, &worklet), - space.ConvertCoordToSpace(wcoords), - Vector2(0.5f, 0.5f)); - - success = result.Valid; - return Vector3(result.Solution[0], result.Solution[1], 0); -} - -static inline VTKM_EXEC vtkm::Vec WorldCoordinatesToParametricCoordinates( - const vtkm::VecAxisAlignedPointCoordinates<2>& pointWCoords, - const vtkm::Vec& wcoords, - vtkm::CellShapeTagQuad, - bool& success, - const FunctorBase&) -{ - success = true; - return (wcoords - pointWCoords.GetOrigin()) / pointWCoords.GetSpacing(); -} template static inline VTKM_EXEC typename WorldCoordVector::ComponentType -WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, - const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagTetra, - bool& success, - const vtkm::exec::FunctorBase& vtkmNotUsed(worklet)) +WorldCoordinatesToParametricCoordinatesTetra( + const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords) { - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 4); - success = true; - // We solve the world to parametric coordinates problem for tetrahedra // similarly to that for triangles. Before understanding this code, you // should understand the triangle code (in ReverseInterpolateTriangle in @@ -1025,16 +934,13 @@ WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, // d = dot((wcoords - p0), planeNormal)/dot((p1-p0), planeNormal) // - using Vector3 = typename WorldCoordVector::ComponentType; + const auto vec0 = pointWCoords[1] - pointWCoords[0]; + const auto vec1 = pointWCoords[2] - pointWCoords[0]; + const auto vec2 = pointWCoords[3] - pointWCoords[0]; + const auto coordVec = wcoords - pointWCoords[0]; - Vector3 pcoords; - - const Vector3 vec0 = pointWCoords[1] - pointWCoords[0]; - const Vector3 vec1 = pointWCoords[2] - pointWCoords[0]; - const Vector3 vec2 = pointWCoords[3] - pointWCoords[0]; - const Vector3 coordVec = wcoords - pointWCoords[0]; - - Vector3 planeNormal = vtkm::Cross(vec1, vec2); + typename WorldCoordVector::ComponentType pcoords; + auto planeNormal = vtkm::Cross(vec1, vec2); pcoords[0] = vtkm::dot(coordVec, planeNormal) / vtkm::dot(vec0, planeNormal); planeNormal = vtkm::Cross(vec0, vec2); @@ -1045,21 +951,94 @@ WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, return pcoords; } +} // detail template static inline VTKM_EXEC typename WorldCoordVector::ComponentType WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, const typename WorldCoordVector::ComponentType& wcoords, - vtkm::CellShapeTagHexahedron, + vtkm::CellShapeTagTetra, bool& success, - const vtkm::exec::FunctorBase& worklet) + const vtkm::exec::FunctorBase&) { - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 8); - - return detail::WorldCoordinatesToParametricCoordinates3D( - pointWCoords, wcoords, vtkm::CellShapeTagHexahedron(), success, worklet); + success = true; + vtkm::exec::internal::FastVec local(pointWCoords); + return detail::WorldCoordinatesToParametricCoordinatesTetra(local.Get(), wcoords); } +//----------------------------------------------------------------------------- +namespace detail +{ + +template +class JacobianFunctor3DCell +{ + using T = typename WorldCoordVector::ComponentType::ComponentType; + using Vector3 = vtkm::Vec; + using Matrix3x3 = vtkm::Matrix; + + const WorldCoordVector* PointWCoords; + +public: + VTKM_EXEC + JacobianFunctor3DCell(const WorldCoordVector* pointWCoords) + : PointWCoords(pointWCoords) + { + } + + VTKM_EXEC + Matrix3x3 operator()(const Vector3& pcoords) const + { + Matrix3x3 jacobian; + vtkm::exec::JacobianFor3DCell(*this->PointWCoords, pcoords, jacobian, CellShapeTag()); + return jacobian; + } +}; + +template +class CoordinatesFunctor3DCell +{ + using T = typename WorldCoordVector::ComponentType::ComponentType; + using Vector3 = vtkm::Vec; + + const WorldCoordVector* PointWCoords; + const vtkm::exec::FunctorBase* Worklet; + +public: + VTKM_EXEC + CoordinatesFunctor3DCell(const WorldCoordVector* pointWCoords, + const vtkm::exec::FunctorBase* worklet) + : PointWCoords(pointWCoords) + , Worklet(worklet) + { + } + + VTKM_EXEC + Vector3 operator()(Vector3 pcoords) const + { + return vtkm::exec::ParametricCoordinatesToWorldCoordinates( + *this->PointWCoords, pcoords, CellShapeTag(), *this->Worklet); + } +}; + +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates3D(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + CellShapeTag, + bool& success, + const vtkm::exec::FunctorBase& worklet) +{ + auto result = vtkm::NewtonsMethod( + JacobianFunctor3DCell(&pointWCoords), + CoordinatesFunctor3DCell(&pointWCoords, &worklet), + wcoords, + typename WorldCoordVector::ComponentType(0.5f, 0.5f, 0.5f)); + success = result.Valid; + return result.Solution; +} +} // detail + static inline VTKM_EXEC vtkm::Vec WorldCoordinatesToParametricCoordinates( const vtkm::VecAxisAlignedPointCoordinates<3>& pointWCoords, const vtkm::Vec& wcoords, @@ -1071,6 +1050,19 @@ static inline VTKM_EXEC vtkm::Vec WorldCoordinatesToParam return (wcoords - pointWCoords.GetOrigin()) / pointWCoords.GetSpacing(); } +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + vtkm::CellShapeTagHexahedron, + bool& success, + const vtkm::exec::FunctorBase& worklet) +{ + vtkm::exec::internal::FastVec local(pointWCoords); + return detail::WorldCoordinatesToParametricCoordinates3D( + local.Get(), wcoords, vtkm::CellShapeTagHexahedron(), success, worklet); +} + template static inline VTKM_EXEC typename WorldCoordVector::ComponentType WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, @@ -1079,10 +1071,9 @@ WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, bool& success, const vtkm::exec::FunctorBase& worklet) { - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 6); - + vtkm::exec::internal::FastVec local(pointWCoords); return detail::WorldCoordinatesToParametricCoordinates3D( - pointWCoords, wcoords, vtkm::CellShapeTagWedge(), success, worklet); + local.Get(), wcoords, vtkm::CellShapeTagWedge(), success, worklet); } template @@ -1093,10 +1084,32 @@ WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, bool& success, const vtkm::exec::FunctorBase& worklet) { - VTKM_ASSERT(pointWCoords.GetNumberOfComponents() == 5); - + vtkm::exec::internal::FastVec local(pointWCoords); return detail::WorldCoordinatesToParametricCoordinates3D( - pointWCoords, wcoords, vtkm::CellShapeTagPyramid(), success, worklet); + local.Get(), wcoords, vtkm::CellShapeTagPyramid(), success, worklet); +} + +//----------------------------------------------------------------------------- +template +static inline VTKM_EXEC typename WorldCoordVector::ComponentType +WorldCoordinatesToParametricCoordinates(const WorldCoordVector& pointWCoords, + const typename WorldCoordVector::ComponentType& wcoords, + vtkm::CellShapeTagGeneric shape, + bool& success, + const vtkm::exec::FunctorBase& worklet) +{ + typename WorldCoordVector::ComponentType result; + switch (shape.Id) + { + vtkmGenericCellShapeMacro(result = WorldCoordinatesToParametricCoordinates( + pointWCoords, wcoords, CellShapeTag(), success, worklet)); + default: + success = false; + worklet.RaiseError("Unknown cell shape sent to world 2 parametric."); + return typename WorldCoordVector::ComponentType(); + } + + return result; } } } // namespace vtkm::exec diff --git a/vtkm/exec/arg/Fetch.h b/vtkm/exec/arg/Fetch.h index bbdb74cc3..753ab721e 100644 --- a/vtkm/exec/arg/Fetch.h +++ b/vtkm/exec/arg/Fetch.h @@ -47,7 +47,7 @@ namespace arg /// object associated where the fetch (nominally) gets its data from. This /// execution object is the data provided by the transport. /// -/// There is no generic implementaiton of \c Fetch. There are partial +/// There is no generic implementation of \c Fetch. There are partial /// specializations of \c Fetch for each mechanism (fetch-aspect tag /// combination) supported. If you get a compiler error about an incomplete /// type for \c Fetch, it means you used an invalid \c FetchTag - \c AspectTag diff --git a/vtkm/exec/arg/FetchTagArrayDirectIn.h b/vtkm/exec/arg/FetchTagArrayDirectIn.h index 74e3c6b36..f5df7e34f 100644 --- a/vtkm/exec/arg/FetchTagArrayDirectIn.h +++ b/vtkm/exec/arg/FetchTagArrayDirectIn.h @@ -32,7 +32,7 @@ namespace arg /// \brief \c Fetch tag for getting array values with direct indexing. /// -/// \c FetchTagArrayDirectIn is a tag used with the \c Fetch class to retreive +/// \c FetchTagArrayDirectIn is a tag used with the \c Fetch class to retrieve /// values from an array portal. The fetch uses direct indexing, so the thread /// index given to \c Load is used as the index into the array. /// diff --git a/vtkm/exec/arg/FetchTagArrayTopologyMapIn.h b/vtkm/exec/arg/FetchTagArrayTopologyMapIn.h index 5c6c89eee..873a4460c 100644 --- a/vtkm/exec/arg/FetchTagArrayTopologyMapIn.h +++ b/vtkm/exec/arg/FetchTagArrayTopologyMapIn.h @@ -43,7 +43,7 @@ namespace arg /// \brief \c Fetch tag for getting array values determined by topology connections. /// /// \c FetchTagArrayTopologyMapIn is a tag used with the \c Fetch class to -/// retreive values from an array portal. The fetch uses indexing based on +/// retrieve values from an array portal. The fetch uses indexing based on /// the topology structure used for the input domain. /// struct FetchTagArrayTopologyMapIn diff --git a/vtkm/exec/arg/FetchTagCellSetIn.h b/vtkm/exec/arg/FetchTagCellSetIn.h index 9801d1a0f..60659c623 100644 --- a/vtkm/exec/arg/FetchTagCellSetIn.h +++ b/vtkm/exec/arg/FetchTagCellSetIn.h @@ -33,7 +33,7 @@ namespace arg /// \brief \c Fetch tag for getting topology information. /// -/// \c FetchTagCellSetIn is a tag used with the \c Fetch class to retreive +/// \c FetchTagCellSetIn is a tag used with the \c Fetch class to retrieve /// values from a topology object. This default parameter returns /// the basis topology type, i.e. cell type in a \c WorkletCellMap. /// diff --git a/vtkm/exec/arg/FetchTagExecObject.h b/vtkm/exec/arg/FetchTagExecObject.h index 2bd03ac14..b2127d6ee 100644 --- a/vtkm/exec/arg/FetchTagExecObject.h +++ b/vtkm/exec/arg/FetchTagExecObject.h @@ -36,7 +36,7 @@ namespace arg /// \brief \c Fetch tag for execution objects. /// -/// \c FetchTagExecObject is a tag used with the \c Fetch class to retreive +/// \c FetchTagExecObject is a tag used with the \c Fetch class to retrieve /// execution objects. For safety, execution objects are read-only. \c /// FetchTagExecObject is almost always used in conjunction with \c /// TransportTagExecObject and vice versa. diff --git a/vtkm/exec/arg/OnBoundary.h b/vtkm/exec/arg/OnBoundary.h index 1a7d37b78..339981029 100644 --- a/vtkm/exec/arg/OnBoundary.h +++ b/vtkm/exec/arg/OnBoundary.h @@ -46,7 +46,7 @@ struct AspectTagOnBoundary struct OnBoundary : vtkm::exec::arg::ExecutionSignatureTagBase { static const vtkm::IdComponent INDEX = 1; - typedef vtkm::exec::arg::AspectTagOnBoundary AspectTag; + using AspectTag = vtkm::exec::arg::AspectTagOnBoundary; }; template diff --git a/vtkm/exec/arg/ThreadIndicesPointNeighborhood.h b/vtkm/exec/arg/ThreadIndicesPointNeighborhood.h index ed289776f..97aebcc1a 100644 --- a/vtkm/exec/arg/ThreadIndicesPointNeighborhood.h +++ b/vtkm/exec/arg/ThreadIndicesPointNeighborhood.h @@ -198,21 +198,21 @@ struct BoundaryState namespace detail { -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// inline VTKM_EXEC vtkm::Id3 To3D(vtkm::Id3 index) { return index; } -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// \overload inline VTKM_EXEC vtkm::Id3 To3D(vtkm::Id2 index) { return vtkm::Id3(index[0], index[1], 1); } -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// \overload inline VTKM_EXEC vtkm::Id3 To3D(vtkm::Vec index) { diff --git a/vtkm/exec/arg/ThreadIndicesTopologyMap.h b/vtkm/exec/arg/ThreadIndicesTopologyMap.h index 640837490..7c1eb5ab3 100644 --- a/vtkm/exec/arg/ThreadIndicesTopologyMap.h +++ b/vtkm/exec/arg/ThreadIndicesTopologyMap.h @@ -36,7 +36,7 @@ namespace detail { /// Most cell shape tags have a default constructor, but the generic cell shape -/// tag does not to prevent accidently losing the Id, which, unlike the other +/// tag does not to prevent accidentally losing the Id, which, unlike the other /// cell shapes, can vary. /// template @@ -158,42 +158,42 @@ private: namespace detail { -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// static inline VTKM_EXEC vtkm::Id3 InflateTo3D(vtkm::Id3 index) { return index; } -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// \overload static inline VTKM_EXEC vtkm::Id3 InflateTo3D(vtkm::Id2 index) { return vtkm::Id3(index[0], index[1], 0); } -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// \overload static inline VTKM_EXEC vtkm::Id3 InflateTo3D(vtkm::Vec index) { return vtkm::Id3(index[0], 0, 0); } -/// Given a \c Vec of (semi) aribtrary size, inflate it to a vtkm::Id3 by padding with zeros. +/// Given a \c Vec of (semi) arbitrary size, inflate it to a vtkm::Id3 by padding with zeros. /// \overload static inline VTKM_EXEC vtkm::Id3 InflateTo3D(vtkm::Id index) { return vtkm::Id3(index, 0, 0); } -/// Given a vtkm::Id3, reduce down to an identifer of choice. +/// Given a vtkm::Id3, reduce down to an identifier of choice. /// static inline VTKM_EXEC vtkm::Id3 Deflate(const vtkm::Id3& index, vtkm::Id3) { return index; } -/// Given a vtkm::Id3, reduce down to an identifer of choice. +/// Given a vtkm::Id3, reduce down to an identifier of choice. /// \overload static inline VTKM_EXEC vtkm::Id2 Deflate(const vtkm::Id3& index, vtkm::Id2) { diff --git a/vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx b/vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx index c223424de..9248e4ced 100644 --- a/vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx +++ b/vtkm/exec/arg/testing/UnitTestFetchArrayNeighborhoodIn.cxx @@ -31,7 +31,7 @@ static const vtkm::Id3 POINT_DIMS = { 10, 4, 16 }; template struct TestPortal { - typedef T ValueType; + using ValueType = T; VTKM_EXEC_CONT vtkm::Id GetNumberOfValues() const { return POINT_DIMS[0] * POINT_DIMS[1] * POINT_DIMS[2]; } @@ -47,7 +47,7 @@ struct TestPortal struct TestIndexPortal { - typedef vtkm::Id ValueType; + using ValueType = vtkm::Id; VTKM_EXEC_CONT ValueType Get(vtkm::Id index) const { return index; } diff --git a/vtkm/exec/cuda/internal/ArrayPortalFromThrust.h b/vtkm/exec/cuda/internal/ArrayPortalFromThrust.h index 6979d9495..8e0777837 100644 --- a/vtkm/exec/cuda/internal/ArrayPortalFromThrust.h +++ b/vtkm/exec/cuda/internal/ArrayPortalFromThrust.h @@ -101,10 +101,7 @@ struct load_through_texture { static const vtkm::IdComponent WillUseTexture = 0; - __device__ static T get(const thrust::system::cuda::pointer& data) - { - return *(data.get()); - } + __device__ static T get(const T* const data) { return *data; } }; //only load through a texture if we have sm 35 support @@ -116,13 +113,13 @@ struct load_through_texture& data) + __device__ static T get(const T* const data) { #if __CUDA_ARCH__ >= 350 // printf("__CUDA_ARCH__ UseScalarTextureLoad"); - return __ldg(data.get()); + return __ldg(data); #else - return *(data.get()); + return *data; #endif } }; @@ -133,62 +130,55 @@ struct load_through_texture& data) + __device__ static T get(const T* const data) { #if __CUDA_ARCH__ >= 350 // printf("__CUDA_ARCH__ UseVecTextureLoads"); return getAs(data); #else - return *(data.get()); + return *data; #endif } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const int2 temp = __ldg((const int2*)data.get()); + const int2 temp = __ldg((const int2*)data); return vtkm::Vec(temp.x, temp.y); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const uint2 temp = __ldg((const uint2*)data.get()); + const uint2 temp = __ldg((const uint2*)data); return vtkm::Vec(temp.x, temp.y); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const int4 temp = __ldg((const int4*)data.get()); + const int4 temp = __ldg((const int4*)data); return vtkm::Vec(temp.x, temp.y, temp.z, temp.w); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const uint4 temp = __ldg((const uint4*)data.get()); + const uint4 temp = __ldg((const uint4*)data); return vtkm::Vec(temp.x, temp.y, temp.z, temp.w); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const float2 temp = __ldg((const float2*)data.get()); + const float2 temp = __ldg((const float2*)data); return vtkm::Vec(temp.x, temp.y); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const float4 temp = __ldg((const float4*)data.get()); + const float4 temp = __ldg((const float4*)data); return vtkm::Vec(temp.x, temp.y, temp.z, temp.w); } - __device__ static vtkm::Vec getAs( - const thrust::system::cuda::pointer>& data) + __device__ static vtkm::Vec getAs(const vtkm::Vec* const data) { - const double2 temp = __ldg((const double2*)data.get()); + const double2 temp = __ldg((const double2*)data); return vtkm::Vec(temp.x, temp.y); } }; @@ -203,22 +193,22 @@ struct load_through_texture< using NonConstT = typename std::remove_const::type; - __device__ static T get(const thrust::system::cuda::pointer& data) + __device__ static T get(const T* const data) { #if __CUDA_ARCH__ >= 350 // printf("__CUDA_ARCH__ UseMultipleScalarTextureLoads"); return getAs(data); #else - return *(data.get()); + return *data; #endif } - __device__ static T getAs(const thrust::system::cuda::pointer& data) + __device__ static T getAs(const T* const data) { //we need to fetch each component individually const vtkm::IdComponent NUM_COMPONENTS = T::NUM_COMPONENTS; using ComponentType = typename T::ComponentType; - const ComponentType* recasted_data = (const ComponentType*)(data.get()); + const ComponentType* recasted_data = (const ComponentType*)(data); NonConstT result; #pragma unroll for (vtkm::IdComponent i = 0; i < NUM_COMPONENTS; ++i) @@ -241,13 +231,13 @@ class ArrayPortalFromThrust : public ArrayPortalFromThrustBase { public: using ValueType = T; - using IteratorType = thrust::system::cuda::pointer; + using IteratorType = T*; + using difference_type = std::ptrdiff_t; VTKM_EXEC_CONT ArrayPortalFromThrust() {} VTKM_CONT - ArrayPortalFromThrust(thrust::system::cuda::pointer begin, - thrust::system::cuda::pointer end) + ArrayPortalFromThrust(IteratorType begin, IteratorType end) : BeginIterator(begin) , EndIterator(end) { @@ -274,15 +264,13 @@ public: VTKM_EXEC_CONT ValueType Get(vtkm::Id index) const { - using SizeType = typename ::thrust::iterator_traits::difference_type; - return *(this->BeginIterator + static_cast(index)); + return *(this->BeginIterator + static_cast(index)); } VTKM_EXEC_CONT void Set(vtkm::Id index, ValueType value) const { - using SizeType = typename ::thrust::iterator_traits::difference_type; - *(this->BeginIterator + static_cast(index)) = value; + *(this->BeginIterator + static_cast(index)) = value; } VTKM_EXEC_CONT @@ -301,13 +289,17 @@ class ConstArrayPortalFromThrust : public ArrayPortalFromThrustBase { public: using ValueType = T; - using IteratorType = thrust::system::cuda::pointer; + using IteratorType = const T*; + using difference_type = std::ptrdiff_t; - VTKM_EXEC_CONT ConstArrayPortalFromThrust() {} + VTKM_EXEC_CONT ConstArrayPortalFromThrust() + : BeginIterator(nullptr) + , EndIterator(nullptr) + { + } VTKM_CONT - ConstArrayPortalFromThrust(const thrust::system::cuda::pointer begin, - const thrust::system::cuda::pointer end) + ConstArrayPortalFromThrust(IteratorType begin, IteratorType end) : BeginIterator(begin) , EndIterator(end) { diff --git a/vtkm/exec/cuda/internal/ExecutionPolicy.h b/vtkm/exec/cuda/internal/ExecutionPolicy.h index f9015ed7e..1dd5d783f 100644 --- a/vtkm/exec/cuda/internal/ExecutionPolicy.h +++ b/vtkm/exec/cuda/internal/ExecutionPolicy.h @@ -44,8 +44,8 @@ struct vtkm_cuda_policy : thrust::device_execution_policy template __host__ __device__ void sort( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, vtkm::exec::cuda::internal::WrappedBinaryPredicate comp) { //sort for concrete pointers and less than op //this makes sure that we invoke the thrust radix sort and not merge sort @@ -55,8 +55,8 @@ __host__ __device__ void sort( template __host__ __device__ void sort_by_key( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, RandomAccessIterator values_first, vtkm::exec::cuda::internal::WrappedBinaryPredicate comp) { //sort for concrete pointers and less than op @@ -68,8 +68,8 @@ __host__ __device__ void sort_by_key( template __host__ __device__ void sort( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, vtkm::exec::cuda::internal::WrappedBinaryPredicate> comp) { //sort for concrete pointers and less than op //this makes sure that we invoke the thrust radix sort and not merge sort @@ -79,8 +79,8 @@ __host__ __device__ void sort( template __host__ __device__ void sort_by_key( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, RandomAccessIterator values_first, vtkm::exec::cuda::internal::WrappedBinaryPredicate> comp) { //sort for concrete pointers and less than op @@ -92,8 +92,8 @@ __host__ __device__ void sort_by_key( template __host__ __device__ void sort( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, vtkm::exec::cuda::internal::WrappedBinaryPredicate comp) { //sort for concrete pointers and greater than op //this makes sure that we invoke the thrust radix sort and not merge sort @@ -103,8 +103,8 @@ __host__ __device__ void sort( template __host__ __device__ void sort_by_key( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, RandomAccessIterator values_first, vtkm::exec::cuda::internal::WrappedBinaryPredicate comp) { //sort for concrete pointers and greater than op @@ -116,8 +116,8 @@ __host__ __device__ void sort_by_key( template __host__ __device__ void sort( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, vtkm::exec::cuda::internal::WrappedBinaryPredicate> comp) { //sort for concrete pointers and greater than op //this makes sure that we invoke the thrust radix sort and not merge sort @@ -127,8 +127,8 @@ __host__ __device__ void sort( template __host__ __device__ void sort_by_key( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer first, - thrust::system::cuda::pointer last, + T* first, + T* last, RandomAccessIterator values_first, vtkm::exec::cuda::internal::WrappedBinaryPredicate> comp) { //sort for concrete pointers and greater than op @@ -174,8 +174,8 @@ template __host__ __device__::thrust::pair reduce_by_key( const vtkm_cuda_policy& exec, - thrust::system::cuda::pointer keys_first, - thrust::system::cuda::pointer keys_last, + T* keys_first, + T* keys_last, InputIterator2 values_first, OutputIterator1 keys_output, OutputIterator2 values_output, diff --git a/vtkm/exec/cuda/internal/WrappedOperators.h b/vtkm/exec/cuda/internal/WrappedOperators.h index 9e6ca4f29..4105b2235 100644 --- a/vtkm/exec/cuda/internal/WrappedOperators.h +++ b/vtkm/exec/cuda/internal/WrappedOperators.h @@ -75,7 +75,7 @@ struct WrappedUnaryPredicate return m_f((T)x); } - VTKM_EXEC bool operator()(const thrust::system::cuda::pointer x) const { return m_f(*x); } + VTKM_EXEC bool operator()(const T* x) const { return m_f(*x); } }; // Binary function object wrapper which can detect and handle calling the @@ -126,26 +126,11 @@ struct WrappedBinaryOperator return m_f((T)x, (T)y); } - VTKM_EXEC T operator()(const thrust::system::cuda::pointer x, const T* y) const - { - return m_f(*x, *y); - } + VTKM_EXEC T operator()(const T* const x, const T& y) const { return m_f(*x, y); } - VTKM_EXEC T operator()(const thrust::system::cuda::pointer x, const T& y) const - { - return m_f(*x, y); - } + VTKM_EXEC T operator()(const T& x, const T* const y) const { return m_f(x, *y); } - VTKM_EXEC T operator()(const T& x, const thrust::system::cuda::pointer y) const - { - return m_f(x, *y); - } - - VTKM_EXEC T operator()(const thrust::system::cuda::pointer x, - const thrust::system::cuda::pointer y) const - { - return m_f(*x, *y); - } + VTKM_EXEC T operator()(const T* const x, const T* const y) const { return m_f(*x, *y); } }; template @@ -192,26 +177,11 @@ struct WrappedBinaryPredicate return m_f((T)x, (T)y); } - VTKM_EXEC bool operator()(const thrust::system::cuda::pointer x, const T* y) const - { - return m_f(*x, *y); - } + VTKM_EXEC bool operator()(const T* const x, const T& y) const { return m_f(*x, y); } - VTKM_EXEC bool operator()(const thrust::system::cuda::pointer x, const T& y) const - { - return m_f(*x, y); - } + VTKM_EXEC bool operator()(const T& x, const T* const y) const { return m_f(x, *y); } - VTKM_EXEC bool operator()(const T& x, const thrust::system::cuda::pointer y) const - { - return m_f(x, *y); - } - - VTKM_EXEC bool operator()(const thrust::system::cuda::pointer x, - const thrust::system::cuda::pointer y) const - { - return m_f(*x, *y); - } + VTKM_EXEC bool operator()(const T* const x, const T* const y) const { return m_f(*x, *y); } }; } } diff --git a/vtkm/exec/internal/CMakeLists.txt b/vtkm/exec/internal/CMakeLists.txt index 31eacb3cf..05cac31ef 100644 --- a/vtkm/exec/internal/CMakeLists.txt +++ b/vtkm/exec/internal/CMakeLists.txt @@ -20,6 +20,7 @@ set(headers ErrorMessageBuffer.h + FastVec.h ReduceByKeyLookup.h TaskSingular.h WorkletInvokeFunctorDetail.h diff --git a/vtkm/exec/internal/FastVec.h b/vtkm/exec/internal/FastVec.h new file mode 100644 index 000000000..7519ab78c --- /dev/null +++ b/vtkm/exec/internal/FastVec.h @@ -0,0 +1,96 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_exec_internal_FastVec_h +#define vtk_m_exec_internal_FastVec_h + +#include +#include + +namespace vtkm +{ +namespace exec +{ +namespace internal +{ + +/// Use this class to convert Vecs of any type to an efficient stack based Vec +/// type. The template parameters are the input Vec type and the maximum +/// number of components it may have. Specializations exist to optimize +/// the copy and stack usage away for already efficient types. +/// This class is useful when several accesses will be performed on +/// potentially inefficient Vec types such as VecFromPortalPermute. +/// +template +class FastVec +{ +public: + using Type = vtkm::VecVariable; + + explicit VTKM_EXEC FastVec(const VecType& vec) + : Vec(vec) + { + } + + VTKM_EXEC const Type& Get() const { return this->Vec; } + +private: + Type Vec; +}; + +template +class FastVec, MaxSize> +{ +public: + using Type = vtkm::Vec; + + explicit VTKM_EXEC FastVec(const Type& vec) + : Vec(vec) + { + VTKM_ASSERT(vec.GetNumberOfComponents() <= MaxSize); + } + + VTKM_EXEC const Type& Get() const { return this->Vec; } + +private: + const Type& Vec; +}; + +template +class FastVec, MaxSize2> +{ +public: + using Type = vtkm::VecVariable; + + explicit VTKM_EXEC FastVec(const Type& vec) + : Vec(vec) + { + VTKM_ASSERT(vec.GetNumberOfComponents() <= MaxSize2); + } + + VTKM_EXEC const Type& Get() const { return this->Vec; } + +private: + const Type& Vec; +}; +} +} +} // vtkm::exec::internal + +#endif // vtk_m_exec_internal_FastVec_h diff --git a/vtkm/exec/testing/UnitTestCellDerivative.cxx b/vtkm/exec/testing/UnitTestCellDerivative.cxx index 04c560458..2728fe43f 100644 --- a/vtkm/exec/testing/UnitTestCellDerivative.cxx +++ b/vtkm/exec/testing/UnitTestCellDerivative.cxx @@ -50,7 +50,7 @@ vtkm::Vec WorldToParametric(const vtkm::Vec& wcoord) return T(0.5) * (wcoord + vtkm::Vec(0.25f)); } -/// Simple structure describing a linear field. Has a convienience class +/// Simple structure describing a linear field. Has a convenience class /// for getting values. template struct LinearField diff --git a/vtkm/filter/CMakeLists.txt b/vtkm/filter/CMakeLists.txt index 1a005696d..bb424f638 100644 --- a/vtkm/filter/CMakeLists.txt +++ b/vtkm/filter/CMakeLists.txt @@ -46,6 +46,7 @@ set(headers PointElevation.h PolicyBase.h PolicyDefault.h + Probe.h Result.h Streamline.h SurfaceNormals.h @@ -81,6 +82,7 @@ set(header_template_sources NDHistogram.hxx PointAverage.hxx PointElevation.hxx + Probe.hxx Streamline.hxx SurfaceNormals.hxx Tetrahedralize.hxx diff --git a/vtkm/filter/ClipWithField.h b/vtkm/filter/ClipWithField.h index 0601d4511..8837d6cf9 100644 --- a/vtkm/filter/ClipWithField.h +++ b/vtkm/filter/ClipWithField.h @@ -71,7 +71,7 @@ template <> class FilterTraits { //currently the Clip filter only works on scalar data. public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/ContourTreeUniform.h b/vtkm/filter/ContourTreeUniform.h index 1dbee0ddd..08d1fbf35 100644 --- a/vtkm/filter/ContourTreeUniform.h +++ b/vtkm/filter/ContourTreeUniform.h @@ -99,7 +99,7 @@ template <> class FilterTraits { public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; /// \brief Construct the ContourTree for a 3D Mesh @@ -127,7 +127,7 @@ template <> class FilterTraits { public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/Entropy.h b/vtkm/filter/Entropy.h index 5385d2b8f..f9d7dbb1c 100644 --- a/vtkm/filter/Entropy.h +++ b/vtkm/filter/Entropy.h @@ -57,7 +57,7 @@ template <> class FilterTraits { public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/ExtractGeometry.h b/vtkm/filter/ExtractGeometry.h index 2f36d53ab..e051fc2ad 100644 --- a/vtkm/filter/ExtractGeometry.h +++ b/vtkm/filter/ExtractGeometry.h @@ -111,7 +111,7 @@ template <> class FilterTraits { //currently the ExtractGeometry filter only works on scalar data. public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/FilterDataSet.hxx b/vtkm/filter/FilterDataSet.hxx index c735f7009..1075cbc2f 100644 --- a/vtkm/filter/FilterDataSet.hxx +++ b/vtkm/filter/FilterDataSet.hxx @@ -138,10 +138,10 @@ inline VTKM_CONT bool FilterDataSet::MapFieldOntoOutput( if (result.IsValid()) { vtkm::filter::FieldMetadata metaData(field); - typedef internal::ResolveFieldTypeAndMap FunctorType; + using FunctorType = internal::ResolveFieldTypeAndMap; FunctorType functor(static_cast(this), result, metaData, policy, valid); - typedef vtkm::filter::FilterTraits Traits; + using Traits = vtkm::filter::FilterTraits; vtkm::cont::CastAndCall( vtkm::filter::ApplyPolicy(field, policy, Traits()), functor, this->Tracker); } diff --git a/vtkm/filter/FilterDataSetWithField.hxx b/vtkm/filter/FilterDataSetWithField.hxx index 1b3981886..794fe0b1c 100644 --- a/vtkm/filter/FilterDataSetWithField.hxx +++ b/vtkm/filter/FilterDataSetWithField.hxx @@ -161,10 +161,10 @@ inline VTKM_CONT Result FilterDataSetWithField::PrepareForExecution( vtkm::filter::FieldMetadata metaData(field); Result result; - typedef internal::ResolveFieldTypeAndExecute FunctorType; + using FunctorType = internal::ResolveFieldTypeAndExecute; FunctorType functor(static_cast(this), input, metaData, policy, result); - typedef vtkm::filter::FilterTraits Traits; + using Traits = vtkm::filter::FilterTraits; vtkm::cont::CastAndCall( vtkm::filter::ApplyPolicy(field, policy, Traits()), functor, this->Tracker); return result; @@ -184,10 +184,10 @@ inline VTKM_CONT Result FilterDataSetWithField::PrepareForExecution( //determine the field type first Result result; - typedef internal::ResolveFieldTypeAndExecute FunctorType; + using FunctorType = internal::ResolveFieldTypeAndExecute; FunctorType functor(static_cast(this), input, metaData, policy, result); - typedef vtkm::filter::FilterTraits Traits; + using Traits = vtkm::filter::FilterTraits; vtkm::cont::CastAndCall( vtkm::filter::ApplyPolicy(field, policy, Traits()), functor, this->Tracker); @@ -215,7 +215,7 @@ inline VTKM_CONT bool FilterDataSetWithField::MapFieldOntoOutput( if (result.IsDataSetValid()) { vtkm::filter::FieldMetadata metaData(field); - typedef internal::ResolveFieldTypeAndMap FunctorType; + using FunctorType = internal::ResolveFieldTypeAndMap; FunctorType functor(static_cast(this), result, metaData, policy, valid); vtkm::cont::CastAndCall(vtkm::filter::ApplyPolicy(field, policy), functor, this->Tracker); diff --git a/vtkm/filter/FilterField.hxx b/vtkm/filter/FilterField.hxx index ca5440633..3d7c5de12 100644 --- a/vtkm/filter/FilterField.hxx +++ b/vtkm/filter/FilterField.hxx @@ -158,10 +158,10 @@ FilterField::PrepareForExecution(const vtkm::cont::DataSet& input, vtkm::filter::FieldMetadata metaData(field); Result result; - typedef internal::ResolveFieldTypeAndExecute FunctorType; + using FunctorType = internal::ResolveFieldTypeAndExecute; FunctorType functor(static_cast(this), input, metaData, policy, result); - typedef vtkm::filter::FilterTraits Traits; + using Traits = vtkm::filter::FilterTraits; vtkm::cont::CastAndCall( vtkm::filter::ApplyPolicy(field, policy, Traits()), functor, this->Tracker); return result; @@ -181,7 +181,7 @@ FilterField::PrepareForExecution(const vtkm::cont::DataSet& input, vtkm::filter::FieldMetadata metaData(field); Result result; - typedef internal::ResolveFieldTypeAndExecute FunctorType; + using FunctorType = internal::ResolveFieldTypeAndExecute; FunctorType functor(static_cast(this), input, metaData, policy, result); vtkm::cont::CastAndCall(field, functor, this->Tracker); diff --git a/vtkm/filter/FilterTraits.h b/vtkm/filter/FilterTraits.h index 1ba23e40d..c023819d0 100644 --- a/vtkm/filter/FilterTraits.h +++ b/vtkm/filter/FilterTraits.h @@ -34,7 +34,7 @@ public: // A filter is able to state what subset of types it supports // by default. By default we use ListTagUniversal to represent that the // filter accepts all types specified by the users provided policy - typedef vtkm::ListTagUniversal InputFieldTypeList; + using InputFieldTypeList = vtkm::ListTagUniversal; }; template diff --git a/vtkm/filter/Gradient.h b/vtkm/filter/Gradient.h index fd30f248e..bbe5236e7 100644 --- a/vtkm/filter/Gradient.h +++ b/vtkm/filter/Gradient.h @@ -129,7 +129,7 @@ public: { }; - typedef TypeListTagGradientInputs InputFieldTypeList; + using InputFieldTypeList = TypeListTagGradientInputs; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/Histogram.h b/vtkm/filter/Histogram.h index 894cdcb72..c2f658e22 100644 --- a/vtkm/filter/Histogram.h +++ b/vtkm/filter/Histogram.h @@ -72,7 +72,7 @@ class FilterTraits //this mainly has to do with getting the ranges for each bin //would require returning a more complex value type public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/MarchingCubes.h b/vtkm/filter/MarchingCubes.h index 05785e682..39afaae24 100644 --- a/vtkm/filter/MarchingCubes.h +++ b/vtkm/filter/MarchingCubes.h @@ -138,7 +138,7 @@ public: : vtkm::ListTagBase { }; - typedef TypeListTagMCScalars InputFieldTypeList; + using InputFieldTypeList = TypeListTagMCScalars; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/MarchingCubes.hxx b/vtkm/filter/MarchingCubes.hxx index 8a17522f6..cc6c7b067 100644 --- a/vtkm/filter/MarchingCubes.hxx +++ b/vtkm/filter/MarchingCubes.hxx @@ -141,7 +141,7 @@ inline VTKM_CONT vtkm::filter::Result MarchingCubes::DoExecute( const vtkm::cont::CoordinateSystem& coords = input.GetCoordinateSystem(this->GetActiveCoordinateSystemIndex()); - typedef vtkm::cont::ArrayHandle> Vec3HandleType; + using Vec3HandleType = vtkm::cont::ArrayHandle>; Vec3HandleType vertices; Vec3HandleType normals; diff --git a/vtkm/filter/PointElevation.h b/vtkm/filter/PointElevation.h index a28672297..f3a5cb904 100644 --- a/vtkm/filter/PointElevation.h +++ b/vtkm/filter/PointElevation.h @@ -66,7 +66,7 @@ class FilterTraits { public: //Point Elevation can only convert Float and Double Vec3 arrays - typedef vtkm::TypeListTagFieldVec3 InputFieldTypeList; + using InputFieldTypeList = vtkm::TypeListTagFieldVec3; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/PolicyBase.h b/vtkm/filter/PolicyBase.h index 466337a7e..e5520f1c5 100644 --- a/vtkm/filter/PolicyBase.h +++ b/vtkm/filter/PolicyBase.h @@ -40,15 +40,15 @@ namespace filter template struct PolicyBase { - typedef VTKM_DEFAULT_TYPE_LIST_TAG FieldTypeList; - typedef VTKM_DEFAULT_STORAGE_LIST_TAG FieldStorageList; + using FieldTypeList = VTKM_DEFAULT_TYPE_LIST_TAG; + using FieldStorageList = VTKM_DEFAULT_STORAGE_LIST_TAG; - typedef vtkm::cont::CellSetListTagStructured StructuredCellSetList; - typedef vtkm::cont::CellSetListTagUnstructured UnstructuredCellSetList; - typedef VTKM_DEFAULT_CELL_SET_LIST_TAG AllCellSetList; + using StructuredCellSetList = vtkm::cont::CellSetListTagStructured; + using UnstructuredCellSetList = vtkm::cont::CellSetListTagUnstructured; + using AllCellSetList = VTKM_DEFAULT_CELL_SET_LIST_TAG; // List of backends to try in sequence (if one fails, the next is attempted). - typedef VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG DeviceAdapterList; + using DeviceAdapterList = VTKM_DEFAULT_DEVICE_ADAPTER_LIST_TAG; }; //----------------------------------------------------------------------------- @@ -57,8 +57,8 @@ VTKM_CONT vtkm::cont::DynamicArrayHandleBase ApplyPolicy(const vtkm::cont::Field& field, const vtkm::filter::PolicyBase&) { - typedef typename DerivedPolicy::FieldTypeList TypeList; - typedef typename DerivedPolicy::FieldStorageList StorageList; + using TypeList = typename DerivedPolicy::FieldTypeList; + using StorageList = typename DerivedPolicy::FieldStorageList; return field.GetData().ResetTypeAndStorageLists(TypeList(), StorageList()); } @@ -71,10 +71,10 @@ ApplyPolicy(const vtkm::cont::Field& field, const vtkm::filter::PolicyBase&, const vtkm::filter::FilterTraits&) { - typedef - typename vtkm::filter::DeduceFilterFieldTypes::TypeList TypeList; + using TypeList = + typename vtkm::filter::DeduceFilterFieldTypes::TypeList; - typedef typename DerivedPolicy::FieldStorageList StorageList; + using StorageList = typename DerivedPolicy::FieldStorageList; return field.GetData().ResetTypeAndStorageLists(TypeList(), StorageList()); } @@ -84,7 +84,7 @@ VTKM_CONT vtkm::cont::DynamicCellSetBase const vtkm::cont::DynamicCellSet& cellset, const vtkm::filter::PolicyBase&) { - typedef typename DerivedPolicy::AllCellSetList CellSetList; + using CellSetList = typename DerivedPolicy::AllCellSetList; return cellset.ResetCellSetList(CellSetList()); } @@ -94,7 +94,7 @@ VTKM_CONT vtkm::cont::DynamicCellSetBase&) { - typedef typename DerivedPolicy::StructuredCellSetList CellSetList; + using CellSetList = typename DerivedPolicy::StructuredCellSetList; return cellset.ResetCellSetList(CellSetList()); } @@ -104,7 +104,7 @@ VTKM_CONT vtkm::cont::DynamicCellSetBase&) { - typedef typename DerivedPolicy::UnstructuredCellSetList CellSetList; + using CellSetList = typename DerivedPolicy::UnstructuredCellSetList; return cellset.ResetCellSetList(CellSetList()); } } diff --git a/vtkm/filter/Probe.h b/vtkm/filter/Probe.h new file mode 100644 index 000000000..f792e50c9 --- /dev/null +++ b/vtkm/filter/Probe.h @@ -0,0 +1,60 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_filter_Probe_h +#define vtk_m_filter_Probe_h + +#include +#include + +namespace vtkm +{ +namespace filter +{ + +class Probe : public vtkm::filter::FilterDataSet +{ +public: + VTKM_CONT + void SetGeometry(const vtkm::cont::DataSet& geometry); + + template + VTKM_CONT vtkm::filter::Result DoExecute(const vtkm::cont::DataSet& input, + const vtkm::filter::PolicyBase& policy, + const DeviceAdapter& device); + + //Map a new field onto the resulting dataset after running the filter + //this call is only valid + template + VTKM_CONT bool DoMapField(vtkm::filter::Result& result, + const vtkm::cont::ArrayHandle& input, + const vtkm::filter::FieldMetadata& fieldMeta, + const vtkm::filter::PolicyBase& policy, + const DeviceAdapter& device); + +private: + vtkm::cont::DataSet Geometry; + vtkm::worklet::Probe Worklet; +}; +} +} // vtkm::filter + +#include + +#endif // vtk_m_filter_Probe_h diff --git a/vtkm/filter/Probe.hxx b/vtkm/filter/Probe.hxx new file mode 100644 index 000000000..3a9ef3402 --- /dev/null +++ b/vtkm/filter/Probe.hxx @@ -0,0 +1,86 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_filter_Probe_hxx +#define vtk_m_filter_Probe_hxx + +namespace vtkm +{ +namespace filter +{ + +VTKM_CONT +inline void Probe::SetGeometry(const vtkm::cont::DataSet& geometry) +{ + this->Geometry = vtkm::cont::DataSet(); + this->Geometry.AddCellSet(geometry.GetCellSet()); + this->Geometry.AddCoordinateSystem(geometry.GetCoordinateSystem()); +} + +template +VTKM_CONT inline vtkm::filter::Result Probe::DoExecute( + const vtkm::cont::DataSet& input, + const vtkm::filter::PolicyBase& policy, + const DeviceAdapter& device) +{ + this->Worklet.Run( + vtkm::filter::ApplyPolicy(input.GetCellSet(this->GetActiveCellSetIndex()), policy), + input.GetCoordinateSystem(this->GetActiveCoordinateSystemIndex()), + this->Geometry.GetCoordinateSystem().GetData(), + device); + + auto output = this->Geometry; + auto hpf = this->Worklet.GetHiddenPointsField(device); + auto hcf = this->Worklet.GetHiddenCellsField( + vtkm::filter::ApplyPolicy(output.GetCellSet(), policy), device); + + output.AddField(vtkm::cont::Field("HIDDEN", vtkm::cont::Field::ASSOC_POINTS, hpf)); + output.AddField(vtkm::cont::Field( + "HIDDEN", vtkm::cont::Field::ASSOC_CELL_SET, output.GetCellSet().GetName(), hcf)); + + return vtkm::filter::Result(output); +} + +template +VTKM_CONT inline bool Probe::DoMapField(vtkm::filter::Result& result, + const vtkm::cont::ArrayHandle& input, + const vtkm::filter::FieldMetadata& fieldMeta, + const vtkm::filter::PolicyBase&, + const DeviceAdapter& device) +{ + if (fieldMeta.IsPointField()) + { + auto fieldArray = + this->Worklet.ProcessPointField(input, device, typename DerivedPolicy::AllCellSetList()); + result.GetDataSet().AddField(fieldMeta.AsField(fieldArray)); + return true; + } + else if (fieldMeta.IsCellField()) + { + auto fieldArray = this->Worklet.ProcessCellField(input, device); + result.GetDataSet().AddField(fieldMeta.AsField(fieldArray)); + return true; + } + + return false; +} +} +} // vtkm::filter + +#endif // vtk_m_filter_Probe_hxx diff --git a/vtkm/filter/Streamline.h b/vtkm/filter/Streamline.h index 20abae892..6c5349ade 100644 --- a/vtkm/filter/Streamline.h +++ b/vtkm/filter/Streamline.h @@ -79,7 +79,7 @@ public: : vtkm::ListTagBase, vtkm::Vec> { }; - typedef TypeListTagStreamline InputFieldTypeList; + using InputFieldTypeList = TypeListTagStreamline; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/Streamline.hxx b/vtkm/filter/Streamline.hxx index ecadb4959..1b194cf24 100644 --- a/vtkm/filter/Streamline.hxx +++ b/vtkm/filter/Streamline.hxx @@ -79,14 +79,12 @@ inline VTKM_CONT vtkm::filter::Result Streamline::DoExecute( return vtkm::filter::Result(); //todo: add check for rectilinear. - typedef vtkm::cont::ArrayHandle> FieldHandle; - typedef - typename FieldHandle::template ExecutionTypes::PortalConst FieldPortalConstType; - typedef vtkm::worklet::particleadvection::UniformGridEvaluate - RGEvalType; - typedef vtkm::worklet::particleadvection::RK4Integrator RK4RGType; + using FieldHandle = vtkm::cont::ArrayHandle>; + using FieldPortalConstType = + typename FieldHandle::template ExecutionTypes::PortalConst; + using RGEvalType = + vtkm::worklet::particleadvection::UniformGridEvaluate; + using RK4RGType = vtkm::worklet::particleadvection::RK4Integrator; //RGEvalType eval(input.GetCoordinateSystem(), input.GetCellSet(0), field); RGEvalType eval(coords, cells, field); diff --git a/vtkm/filter/Threshold.h b/vtkm/filter/Threshold.h index ec80d9595..80fef774e 100644 --- a/vtkm/filter/Threshold.h +++ b/vtkm/filter/Threshold.h @@ -80,7 +80,7 @@ template <> class FilterTraits { //currently the threshold filter only works on scalar data. public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/ThresholdPoints.h b/vtkm/filter/ThresholdPoints.h index c974efb34..e85cfb51d 100644 --- a/vtkm/filter/ThresholdPoints.h +++ b/vtkm/filter/ThresholdPoints.h @@ -89,7 +89,7 @@ template <> class FilterTraits { //currently the threshold filter only works on scalar data. public: - typedef TypeListTagScalarAll InputFieldTypeList; + using InputFieldTypeList = TypeListTagScalarAll; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/VectorMagnitude.h b/vtkm/filter/VectorMagnitude.h index 3099ef756..8c0f8e0e9 100644 --- a/vtkm/filter/VectorMagnitude.h +++ b/vtkm/filter/VectorMagnitude.h @@ -50,7 +50,7 @@ template <> class FilterTraits { //currently the VectorMagnitude filter only works on vector data. public: - typedef TypeListTagVecCommon InputFieldTypeList; + using InputFieldTypeList = TypeListTagVecCommon; }; } } // namespace vtkm::filter diff --git a/vtkm/filter/VectorMagnitude.hxx b/vtkm/filter/VectorMagnitude.hxx index d688be439..d3066b617 100644 --- a/vtkm/filter/VectorMagnitude.hxx +++ b/vtkm/filter/VectorMagnitude.hxx @@ -42,7 +42,7 @@ inline VTKM_CONT vtkm::filter::Result VectorMagnitude::DoExecute( const vtkm::filter::PolicyBase&, const DeviceAdapter&) { - typedef typename detail::FloatingPointReturnType::Type ReturnType; + using ReturnType = typename detail::FloatingPointReturnType::Type; vtkm::cont::ArrayHandle outArray; vtkm::worklet::DispatcherMapField dispatcher( diff --git a/vtkm/filter/internal/ResolveFieldTypeAndExecute.h b/vtkm/filter/internal/ResolveFieldTypeAndExecute.h index 98bf1847a..cd9b247e5 100644 --- a/vtkm/filter/internal/ResolveFieldTypeAndExecute.h +++ b/vtkm/filter/internal/ResolveFieldTypeAndExecute.h @@ -50,7 +50,7 @@ struct ResolveFieldTypeAndExecuteForDevice template struct ResolveFieldTypeAndExecute { - typedef ResolveFieldTypeAndExecute Self; + using Self = ResolveFieldTypeAndExecute; Derived* DerivedClass; const vtkm::cont::DataSet& InputData; diff --git a/vtkm/filter/internal/ResolveFieldTypeAndMap.h b/vtkm/filter/internal/ResolveFieldTypeAndMap.h index 379aef2ae..554b65913 100644 --- a/vtkm/filter/internal/ResolveFieldTypeAndMap.h +++ b/vtkm/filter/internal/ResolveFieldTypeAndMap.h @@ -56,7 +56,7 @@ struct ResolveFieldTypeAndMapForDevice template struct ResolveFieldTypeAndMap { - typedef ResolveFieldTypeAndMap Self; + using Self = ResolveFieldTypeAndMap; Derived* DerivedClass; vtkm::filter::Result& InputResult; diff --git a/vtkm/filter/testing/CMakeLists.txt b/vtkm/filter/testing/CMakeLists.txt index fb0861572..7756a4897 100644 --- a/vtkm/filter/testing/CMakeLists.txt +++ b/vtkm/filter/testing/CMakeLists.txt @@ -40,6 +40,7 @@ set(unit_tests UnitTestNDHistogramFilter.cxx UnitTestPointAverageFilter.cxx UnitTestPointElevationFilter.cxx + UnitTestProbe.cxx UnitTestStreamlineFilter.cxx UnitTestSurfaceNormalsFilter.cxx UnitTestTetrahedralizeFilter.cxx diff --git a/vtkm/filter/testing/UnitTestClipWithFieldFilter.cxx b/vtkm/filter/testing/UnitTestClipWithFieldFilter.cxx index bdbc88ba9..f92f9f923 100644 --- a/vtkm/filter/testing/UnitTestClipWithFieldFilter.cxx +++ b/vtkm/filter/testing/UnitTestClipWithFieldFilter.cxx @@ -27,7 +27,7 @@ namespace { -typedef vtkm::Vec Coord3D; +using Coord3D = vtkm::Vec; vtkm::cont::DataSet MakeTestDatasetExplicit() { diff --git a/vtkm/filter/testing/UnitTestClipWithImplicitFunctionFilter.cxx b/vtkm/filter/testing/UnitTestClipWithImplicitFunctionFilter.cxx index 1a7c0fc3d..6e8960536 100644 --- a/vtkm/filter/testing/UnitTestClipWithImplicitFunctionFilter.cxx +++ b/vtkm/filter/testing/UnitTestClipWithImplicitFunctionFilter.cxx @@ -27,7 +27,7 @@ namespace { -typedef vtkm::Vec Coord3D; +using Coord3D = vtkm::Vec; vtkm::cont::DataSet MakeTestDatasetStructured() { diff --git a/vtkm/filter/testing/UnitTestEntropyFilter.cxx b/vtkm/filter/testing/UnitTestEntropyFilter.cxx index 21da3a96e..7ffe8a386 100644 --- a/vtkm/filter/testing/UnitTestEntropyFilter.cxx +++ b/vtkm/filter/testing/UnitTestEntropyFilter.cxx @@ -33,7 +33,7 @@ class TangleField : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn vertexId, FieldOut v); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; const vtkm::Id xdim, ydim, zdim; const vtkm::Float32 xmin, ymin, zmin, xmax, ymax, zmax; diff --git a/vtkm/filter/testing/UnitTestExternalFacesFilter.cxx b/vtkm/filter/testing/UnitTestExternalFacesFilter.cxx index ae7888572..b3b858b10 100644 --- a/vtkm/filter/testing/UnitTestExternalFacesFilter.cxx +++ b/vtkm/filter/testing/UnitTestExternalFacesFilter.cxx @@ -93,8 +93,8 @@ void TestExternalFacesExplicitGrid(const vtkm::cont::DataSet& ds, VTKM_TEST_ASSERT(numOutputExtFaces == numExpectedExtFaces, "Number of External Faces mismatch"); // verify fields - VTKM_TEST_ASSERT(resultds.HasField("pointvar"), "Point field not mapped succesfully"); - VTKM_TEST_ASSERT(resultds.HasField("cellvar"), "Cell field not mapped succesfully"); + VTKM_TEST_ASSERT(resultds.HasField("pointvar"), "Point field not mapped successfully"); + VTKM_TEST_ASSERT(resultds.HasField("cellvar"), "Cell field not mapped successfully"); // verify CompactPoints if (compactPoints) diff --git a/vtkm/filter/testing/UnitTestGradient.cxx b/vtkm/filter/testing/UnitTestGradient.cxx index 8af46cecf..a48b06daa 100644 --- a/vtkm/filter/testing/UnitTestGradient.cxx +++ b/vtkm/filter/testing/UnitTestGradient.cxx @@ -37,8 +37,8 @@ void TestCellGradientUniform3D() vtkm::filter::Gradient gradient; gradient.SetOutputFieldName("Gradient"); - gradient.SetComputeVorticity(true); //this wont work as we have a scalar field - gradient.SetComputeQCriterion(true); //this wont work as we have a scalar field + gradient.SetComputeVorticity(true); //this won't work as we have a scalar field + gradient.SetComputeQCriterion(true); //this won't work as we have a scalar field result = gradient.Execute(dataSet, dataSet.GetField("pointvar")); diff --git a/vtkm/filter/testing/UnitTestMarchingCubesFilter.cxx b/vtkm/filter/testing/UnitTestMarchingCubesFilter.cxx index 56ec5cc8a..26abb0e3d 100644 --- a/vtkm/filter/testing/UnitTestMarchingCubesFilter.cxx +++ b/vtkm/filter/testing/UnitTestMarchingCubesFilter.cxx @@ -38,7 +38,7 @@ class TangleField : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn vertexId, FieldOut v); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; const vtkm::Id xdim, ydim, zdim; const vtkm::FloatDefault xmin, ymin, zmin, xmax, ymax, zmax; @@ -167,8 +167,8 @@ public: VTKM_EXEC_CONT vtkm::Id operator()(vtkm::Id vertex) const { - typedef vtkm::CellShapeTagHexahedron HexTag; - typedef vtkm::CellTraits HexTraits; + using HexTag = vtkm::CellShapeTagHexahedron; + using HexTraits = vtkm::CellTraits; vtkm::Id cellId = vertex / HexTraits::NUM_POINTS; vtkm::Id localId = vertex % HexTraits::NUM_POINTS; @@ -208,30 +208,28 @@ private: class MakeRadiantDataSet { public: - typedef vtkm::cont::ArrayHandleUniformPointCoordinates CoordinateArrayHandle; - typedef vtkm::cont::ArrayHandleTransform - DataArrayHandle; - typedef vtkm::cont::ArrayHandleTransform, - CubeGridConnectivity> - ConnectivityArrayHandle; - - typedef vtkm::cont::CellSetSingleType< + using CoordinateArrayHandle = vtkm::cont::ArrayHandleUniformPointCoordinates; + using DataArrayHandle = + vtkm::cont::ArrayHandleTransform; + using ConnectivityArrayHandle = vtkm::cont::ArrayHandleTransform, - CubeGridConnectivity>::StorageTag> - CellSet; + CubeGridConnectivity>; + + using CellSet = vtkm::cont::CellSetSingleType< + vtkm::cont::ArrayHandleTransform, + CubeGridConnectivity>::StorageTag>; vtkm::cont::DataSet Make3DRadiantDataSet(vtkm::IdComponent dim = 5); }; class PolicyRadiantDataSet : public vtkm::filter::PolicyBase { - typedef MakeRadiantDataSet::DataArrayHandle DataHandleType; - typedef MakeRadiantDataSet::ConnectivityArrayHandle CountingHandleType; + using DataHandleType = MakeRadiantDataSet::DataArrayHandle; + using CountingHandleType = MakeRadiantDataSet::ConnectivityArrayHandle; - typedef vtkm::cont::ArrayHandleTransform, - CubeGridConnectivity> - TransformHandleType; + using TransformHandleType = + vtkm::cont::ArrayHandleTransform, + CubeGridConnectivity>; public: struct TypeListTagRadiantTypes : vtkm::ListTagBase { }; - typedef TypeListTagRadiantCellSetTypes AllCellSetList; + using AllCellSetList = TypeListTagRadiantCellSetTypes; }; inline vtkm::cont::DataSet MakeRadiantDataSet::Make3DRadiantDataSet(vtkm::IdComponent dim) @@ -256,10 +254,10 @@ inline vtkm::cont::DataSet MakeRadiantDataSet::Make3DRadiantDataSet(vtkm::IdComp vtkm::cont::DataSet dataSet; - typedef vtkm::CellShapeTagHexahedron HexTag; - typedef vtkm::CellTraits HexTraits; + using HexTag = vtkm::CellShapeTagHexahedron; + using HexTraits = vtkm::CellTraits; - typedef vtkm::Vec CoordType; + using CoordType = vtkm::Vec; const vtkm::IdComponent nCells = dim * dim * dim; @@ -327,7 +325,7 @@ void TestMarchingCubesUniformGrid() vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem(); vtkm::cont::DynamicCellSet dcells = outputData.GetCellSet(); - typedef vtkm::cont::CellSetSingleType<> CellSetType; + using CellSetType = vtkm::cont::CellSetSingleType<>; const CellSetType& cells = dcells.Cast(); //verify that the number of points is correct (72) @@ -351,7 +349,7 @@ void TestMarchingCubesUniformGrid() //verify that the number of cells is correct (160) vtkm::cont::DynamicCellSet dcells = outputData.GetCellSet(); - typedef vtkm::cont::CellSetSingleType<> CellSetType; + using CellSetType = vtkm::cont::CellSetSingleType<>; const CellSetType& cells = dcells.Cast(); VTKM_TEST_ASSERT(cells.GetNumberOfCells() == 160, ""); } @@ -361,7 +359,7 @@ void TestMarchingCubesCustomPolicy() { std::cout << "Testing MarchingCubes filter with custom field and cellset" << std::endl; - typedef MakeRadiantDataSet DataSetGenerator; + using DataSetGenerator = MakeRadiantDataSet; DataSetGenerator dataSetGenerator; const vtkm::IdComponent Dimension = 10; diff --git a/vtkm/filter/testing/UnitTestProbe.cxx b/vtkm/filter/testing/UnitTestProbe.cxx new file mode 100644 index 000000000..31f93c006 --- /dev/null +++ b/vtkm/filter/testing/UnitTestProbe.cxx @@ -0,0 +1,246 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#include + +#include +#include +#include + +#include + +namespace +{ + +vtkm::cont::DataSet MakeInputDataSet() +{ + std::vector pvec(16), cvec(9); + for (std::size_t i = 0; i < 16; ++i) + { + pvec[i] = static_cast(i) * 0.3f; + } + for (std::size_t i = 0; i < 9; ++i) + { + cvec[i] = static_cast(i) * 0.7f; + } + + auto input = vtkm::cont::DataSetBuilderUniform::Create( + vtkm::Id2(4, 4), vtkm::make_Vec(0.0f, 0.0f), vtkm::make_Vec(1.0f, 1.0f)); + vtkm::cont::DataSetFieldAdd::AddPointField(input, "pointdata", pvec); + vtkm::cont::DataSetFieldAdd::AddCellField(input, "celldata", cvec); + return input; +} + +vtkm::cont::DataSet MakeGeometryDataSet() +{ + auto geometry = vtkm::cont::DataSetBuilderUniform::Create( + vtkm::Id2(9, 9), vtkm::make_Vec(0.7f, 0.7f), vtkm::make_Vec(0.35f, 0.35f)); + return geometry; +} + +struct ConvertImpl +{ + template + bool operator()(DeviceAdapter device, + const vtkm::cont::DataSet& uds, + vtkm::cont::DataSet& eds) const + { + vtkm::cont::CellSetExplicit<> cs(uds.GetCellSet().GetName()); + vtkm::worklet::CellDeepCopy::Run(uds.GetCellSet(), cs, device); + eds.AddCellSet(cs); + + vtkm::cont::ArrayHandle> points; + vtkm::cont::DeviceAdapterAlgorithm::Copy(uds.GetCoordinateSystem().GetData(), + points); + eds.AddCoordinateSystem( + vtkm::cont::CoordinateSystem(uds.GetCoordinateSystem().GetName(), points)); + + for (vtkm::IdComponent i = 0; i < uds.GetNumberOfFields(); ++i) + { + eds.AddField(uds.GetField(i)); + } + + return true; + } +}; + +vtkm::cont::DataSet ConvertDataSetUniformToExplicit(const vtkm::cont::DataSet& uds) +{ + vtkm::cont::DataSet eds; + vtkm::cont::TryExecute(ConvertImpl(), uds, eds); + return eds; +} + +const std::vector& GetExpectedPointData() +{ + static std::vector expected = { + 1.05f, 1.155f, 1.26f, 1.365f, 1.47f, 1.575f, 1.68f, 0.0f, 0.0f, 1.47f, 1.575f, 1.68f, + 1.785f, 1.89f, 1.995f, 2.1f, 0.0f, 0.0f, 1.89f, 1.995f, 2.1f, 2.205f, 2.31f, 2.415f, + 2.52f, 0.0f, 0.0f, 2.31f, 2.415f, 2.52f, 2.625f, 2.73f, 2.835f, 2.94f, 0.0f, 0.0f, + 2.73f, 2.835f, 2.94f, 3.045f, 3.15f, 3.255f, 3.36f, 0.0f, 0.0f, 3.15f, 3.255f, 3.36f, + 3.465f, 3.57f, 3.675f, 3.78f, 0.0f, 0.0f, 3.57f, 3.675f, 3.78f, 3.885f, 3.99f, 4.095f, + 4.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + return expected; +} + +const std::vector& GetExpectedCellData() +{ + static std::vector expected = { + 0.0f, 0.7f, 0.7f, 0.7f, 1.4f, 1.4f, 1.4f, 0.0f, 0.0f, 2.1f, 2.8f, 2.8f, 2.8f, 3.5f, + 3.5f, 3.5f, 0.0f, 0.0f, 2.1f, 2.8f, 2.8f, 2.8f, 3.5f, 3.5f, 3.5f, 0.0f, 0.0f, 2.1f, + 2.8f, 2.8f, 2.8f, 3.5f, 3.5f, 3.5f, 0.0f, 0.0f, 4.2f, 4.9f, 4.9f, 4.9f, 5.6f, 5.6f, + 5.6f, 0.0f, 0.0f, 4.2f, 4.9f, 4.9f, 4.9f, 5.6f, 5.6f, 5.6f, 0.0f, 0.0f, 4.2f, 4.9f, + 4.9f, 4.9f, 5.6f, 5.6f, 5.6f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + return expected; +} + +const std::vector& GetExpectedHiddenPoints() +{ + static std::vector expected = { 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, + 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, + 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; + return expected; +} + +const std::vector& GetExpectedHiddenCells() +{ + static std::vector expected = { 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; + return expected; +} + +template +void TestResultArray(const vtkm::cont::ArrayHandle& result, const std::vector& expected) +{ + VTKM_TEST_ASSERT(result.GetNumberOfValues() == static_cast(expected.size()), + "Incorrect field size"); + + auto portal = result.GetPortalConstControl(); + vtkm::Id size = portal.GetNumberOfValues(); + for (vtkm::Id i = 0; i < size; ++i) + { + VTKM_TEST_ASSERT(test_equal(portal.Get(i), expected[static_cast(i)]), + "Incorrect field value"); + } +} + +class TestProbe +{ +private: + using FieldArrayType = vtkm::cont::ArrayHandle; + using HiddenArrayType = vtkm::cont::ArrayHandle; + + static void ExplicitToUnifrom() + { + std::cout << "Testing Probe Explicit to Uniform:\n"; + + auto input = ConvertDataSetUniformToExplicit(MakeInputDataSet()); + auto geometry = MakeGeometryDataSet(); + + vtkm::filter::Probe probe; + probe.SetGeometry(geometry); + auto result = probe.Execute(input); + probe.MapFieldOntoOutput(result, input.GetField("pointdata")); + probe.MapFieldOntoOutput(result, input.GetField("celldata")); + + auto output = result.GetDataSet(); + + TestResultArray(output.GetField("pointdata").GetData().template Cast(), + GetExpectedPointData()); + TestResultArray(output.GetField("celldata").GetData().template Cast(), + GetExpectedCellData()); + TestResultArray(output.GetPointField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenPoints()); + TestResultArray(output.GetCellField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenCells()); + } + + static void UniformToExplict() + { + std::cout << "Testing Probe Uniform to Explicit:\n"; + + auto input = MakeInputDataSet(); + auto geometry = ConvertDataSetUniformToExplicit(MakeGeometryDataSet()); + + vtkm::filter::Probe probe; + probe.SetGeometry(geometry); + auto result = probe.Execute(input); + probe.MapFieldOntoOutput(result, input.GetField("pointdata")); + probe.MapFieldOntoOutput(result, input.GetField("celldata")); + + auto output = result.GetDataSet(); + + TestResultArray(output.GetField("pointdata").GetData().template Cast(), + GetExpectedPointData()); + TestResultArray(output.GetField("celldata").GetData().template Cast(), + GetExpectedCellData()); + TestResultArray(output.GetPointField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenPoints()); + TestResultArray(output.GetCellField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenCells()); + } + + static void ExplicitToExplict() + { + std::cout << "Testing Probe Explicit to Explicit:\n"; + + auto input = ConvertDataSetUniformToExplicit(MakeInputDataSet()); + auto geometry = ConvertDataSetUniformToExplicit(MakeGeometryDataSet()); + + vtkm::filter::Probe probe; + probe.SetGeometry(geometry); + auto result = probe.Execute(input); + probe.MapFieldOntoOutput(result, input.GetField("pointdata")); + probe.MapFieldOntoOutput(result, input.GetField("celldata")); + + auto output = result.GetDataSet(); + + TestResultArray(output.GetField("pointdata").GetData().template Cast(), + GetExpectedPointData()); + TestResultArray(output.GetField("celldata").GetData().template Cast(), + GetExpectedCellData()); + TestResultArray(output.GetPointField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenPoints()); + TestResultArray(output.GetCellField("HIDDEN").GetData().template Cast(), + GetExpectedHiddenCells()); + } + +public: + static void Run() + { + ExplicitToUnifrom(); + UniformToExplict(); + ExplicitToExplict(); + } +}; + +} // anonymous namespace + +int UnitTestProbe(int, char* []) +{ + return vtkm::cont::testing::Testing::Run(TestProbe::Run); +} diff --git a/vtkm/filter/testing/UnitTestVertexClusteringFilter.cxx b/vtkm/filter/testing/UnitTestVertexClusteringFilter.cxx index 73439ef6d..2c97ceeb0 100644 --- a/vtkm/filter/testing/UnitTestVertexClusteringFilter.cxx +++ b/vtkm/filter/testing/UnitTestVertexClusteringFilter.cxx @@ -67,7 +67,7 @@ void TestVertexClustering() vtkm::Float32 output_cellvar[] = { 145.f, 134.f, 138.f, 140.f, 149.f, 144.f }; { - typedef vtkm::cont::CellSetSingleType<> CellSetType; + using CellSetType = vtkm::cont::CellSetSingleType<>; CellSetType cellSet; output.GetCellSet(0).CopyTo(cellSet); auto cellArray = @@ -87,7 +87,7 @@ void TestVertexClustering() vtkm::cont::printSummary_ArrayHandle(pointvar, std::cerr, true); vtkm::cont::printSummary_ArrayHandle(cellvar, std::cerr, true); - typedef vtkm::Vec PointType; + using PointType = vtkm::Vec; auto pointArray = output.GetCoordinateSystem(0).GetData(); VTKM_TEST_ASSERT(pointArray.GetNumberOfValues() == output_points, "Number of output points mismatch"); diff --git a/vtkm/internal/ArrayPortalUniformPointCoordinates.h b/vtkm/internal/ArrayPortalUniformPointCoordinates.h index 89d86a130..bab57e005 100644 --- a/vtkm/internal/ArrayPortalUniformPointCoordinates.h +++ b/vtkm/internal/ArrayPortalUniformPointCoordinates.h @@ -33,7 +33,7 @@ namespace internal class VTKM_ALWAYS_EXPORT ArrayPortalUniformPointCoordinates { public: - typedef vtkm::Vec ValueType; + using ValueType = vtkm::Vec; VTKM_EXEC_CONT ArrayPortalUniformPointCoordinates() diff --git a/vtkm/internal/ArrayPortalValueReference.h b/vtkm/internal/ArrayPortalValueReference.h index 55c73ae52..33842fc00 100644 --- a/vtkm/internal/ArrayPortalValueReference.h +++ b/vtkm/internal/ArrayPortalValueReference.h @@ -32,7 +32,7 @@ namespace internal /// \brief A value class for returning setable values of an ArrayPortal /// /// \c ArrayPortal classes have a pair of \c Get and \c Set methods that -/// retreive and store values in the array. This is to make it easy to +/// retrieve and store values in the array. This is to make it easy to /// implement the \c ArrayPortal even it is not really an array. However, there /// are some cases where the code structure expects a reference to a value that /// can be set. For example, the \c IteratorFromArrayPortal class must return diff --git a/vtkm/internal/Configure.h.in b/vtkm/internal/Configure.h.in index c8d0618c2..a1eb9022a 100644 --- a/vtkm/internal/Configure.h.in +++ b/vtkm/internal/Configure.h.in @@ -85,6 +85,11 @@ #define VTKM_SIZE_LONG @VTKm_SIZE_LONG@ #define VTKM_SIZE_LONG_LONG @VTKm_SIZE_LONG_LONG@ +// Defines the cache line size in bytes to align allocations to +#ifndef VTKM_ALLOCATION_ALIGNMENT +#define VTKM_ALLOCATION_ALIGNMENT 64 +#endif + // Define a pair of macros, VTKM_THIRDPARTY_PRE_INCLUDE and VTKM_THIRDPARTY_POST_INCLUDE, // that should be wrapped around any #include for a tbb or thrust header file. Mostly // this is used to set pragmas that dissable warnings that VTK-m checks for @@ -269,7 +274,7 @@ #ifdef VTKM_MSVC //With MSVC the types that we generate cause warning C4503 (long symbol names) -//this doesn't affect the resulting binary so we just supress that warning +//this doesn't affect the resulting binary so we just suppress that warning // #pragma warning(disable:4503) @@ -279,7 +284,7 @@ //a valid use is MSVC-specific. Even less fortunate is the fact that if //another header violates the warning, it is impossible to suppress it //because it happens in a system header file (xutility), which was included -//far before the actual offending code occured. Even less fortunate than +//far before the actual offending code occurred. Even less fortunate than //that, a boost header we (indirectly) use sets off this warning, cannot //be suppressed, and is not going to be fixed //(https://svn.boost.org/trac/boost/ticket/11426). The best solution is to diff --git a/vtkm/internal/ConnectivityStructuredInternals.h b/vtkm/internal/ConnectivityStructuredInternals.h index b6af0ea08..724280a03 100644 --- a/vtkm/internal/ConnectivityStructuredInternals.h +++ b/vtkm/internal/ConnectivityStructuredInternals.h @@ -40,7 +40,7 @@ template <> class ConnectivityStructuredInternals<1> { public: - typedef vtkm::Id SchedulingRangeType; + using SchedulingRangeType = vtkm::Id; VTKM_EXEC_CONT void SetPointDimensions(vtkm::Id dimensions) { this->PointDimensions = dimensions; } @@ -75,7 +75,7 @@ public: VTKM_EXEC_CONT vtkm::IdComponent GetCellShape() const { return vtkm::CELL_SHAPE_LINE; } - typedef vtkm::CellShapeTagLine CellShapeTag; + using CellShapeTag = vtkm::CellShapeTagLine; VTKM_EXEC_CONT vtkm::Vec GetPointsOfCell(vtkm::Id index) const @@ -145,7 +145,7 @@ template <> class ConnectivityStructuredInternals<2> { public: - typedef vtkm::Id2 SchedulingRangeType; + using SchedulingRangeType = vtkm::Id2; VTKM_EXEC_CONT void SetPointDimensions(vtkm::Id2 dims) { this->PointDimensions = dims; } @@ -181,7 +181,7 @@ public: VTKM_EXEC_CONT vtkm::IdComponent GetCellShape() const { return vtkm::CELL_SHAPE_QUAD; } - typedef vtkm::CellShapeTagQuad CellShapeTag; + using CellShapeTag = vtkm::CellShapeTagQuad; VTKM_EXEC_CONT vtkm::Vec GetPointsOfCell( @@ -303,7 +303,7 @@ template <> class ConnectivityStructuredInternals<3> { public: - typedef vtkm::Id3 SchedulingRangeType; + using SchedulingRangeType = vtkm::Id3; VTKM_EXEC_CONT void SetPointDimensions(vtkm::Id3 dims) @@ -344,7 +344,7 @@ public: VTKM_EXEC_CONT vtkm::IdComponent GetCellShape() const { return vtkm::CELL_SHAPE_HEXAHEDRON; } - typedef vtkm::CellShapeTagHexahedron CellShapeTag; + using CellShapeTag = vtkm::CellShapeTagHexahedron; VTKM_EXEC_CONT vtkm::Vec GetPointsOfCell(const SchedulingRangeType& ijk) const @@ -512,12 +512,12 @@ struct ConnectivityStructuredIndexHelper { - typedef vtkm::internal::ConnectivityStructuredInternals ConnectivityType; - typedef typename ConnectivityType::SchedulingRangeType LogicalIndexType; + using ConnectivityType = vtkm::internal::ConnectivityStructuredInternals; + using LogicalIndexType = typename ConnectivityType::SchedulingRangeType; using CellShapeTag = typename ConnectivityType::CellShapeTag; - typedef vtkm::Vec IndicesType; + using IndicesType = vtkm::Vec; VTKM_EXEC_CONT static vtkm::Id GetNumberOfElements(const ConnectivityType& connectivity) { @@ -573,12 +573,12 @@ struct ConnectivityStructuredIndexHelper { - typedef vtkm::internal::ConnectivityStructuredInternals ConnectivityType; - typedef typename ConnectivityType::SchedulingRangeType LogicalIndexType; + using ConnectivityType = vtkm::internal::ConnectivityStructuredInternals; + using LogicalIndexType = typename ConnectivityType::SchedulingRangeType; using CellShapeTag = vtkm::CellShapeTagVertex; - typedef vtkm::VecVariable IndicesType; + using IndicesType = vtkm::VecVariable; VTKM_EXEC_CONT static vtkm::Id GetNumberOfElements(const ConnectivityType& connectivity) { diff --git a/vtkm/internal/FunctionInterface.h b/vtkm/internal/FunctionInterface.h index 828231bb2..5565a656c 100644 --- a/vtkm/internal/FunctionInterface.h +++ b/vtkm/internal/FunctionInterface.h @@ -102,7 +102,7 @@ class FunctionInterfaceDynamicTransformContContinue; /// series of transformations and operations can occur. /// /// Supporting arbitrary function and template arguments is difficult and -/// really requires seperate implementations for ANSI and C++11 versions of +/// really requires separate implementations for ANSI and C++11 versions of /// compilers. Thus, variatic template arguments are, at this point in time, /// something to be avoided when possible. The intention of \c /// FunctionInterface is to collect most of the variatic template code into one @@ -234,7 +234,7 @@ class FunctionInterface friend class FunctionInterface; public: - typedef FunctionSignature Signature; + using Signature = FunctionSignature; VTKM_SUPPRESS_EXEC_WARNINGS FunctionInterface() @@ -251,16 +251,16 @@ public: } // the number of parameters as an integral constant - typedef detail::FunctionSigInfo SigInfo; - typedef typename SigInfo::ArityType SignatureArity; - typedef typename SigInfo::ResultType ResultType; - typedef typename SigInfo::Components ComponentSig; - typedef typename SigInfo::Parameters ParameterSig; + using SigInfo = detail::FunctionSigInfo; + using SignatureArity = typename SigInfo::ArityType; + using ResultType = typename SigInfo::ResultType; + using ComponentSig = typename SigInfo::Components; + using ParameterSig = typename SigInfo::Parameters; template struct ParameterType { - typedef typename detail::AtType::type type; + using type = typename detail::AtType::type; }; static const bool RETURN_VALID = FunctionInterfaceReturnContainer::VALID; @@ -474,7 +474,7 @@ public: template VTKM_CONT typename AppendType::type Append(const NewType& newParameter) const { - typedef typename detail::AppendType::type AppendSignature; + using AppendSignature = typename detail::AppendType::type; FunctionInterface appendedFuncInterface; appendedFuncInterface.Copy(*this); @@ -532,8 +532,8 @@ public: vtkm::internal::IndexTag = vtkm::internal::IndexTag()) const { - typedef - typename detail::ReplaceType::type ReplaceSigType; + using ReplaceSigType = + typename detail::ReplaceType::type; FunctionInterface replacedFuncInterface; detail::FunctionInterfaceMoveParameters::Move( @@ -549,9 +549,8 @@ public: template struct StaticTransformType { - typedef FunctionInterface< - typename detail::FunctionInterfaceStaticTransformType::type> - type; + using type = FunctionInterface< + typename detail::FunctionInterfaceStaticTransformType::type>; }; /// \brief Transforms the \c FunctionInterface based on compile-time @@ -695,11 +694,11 @@ public: VTKM_CONT void DynamicTransformCont(const TransformFunctor& transform, const FinishFunctor& finish) const { - typedef detail::FunctionInterfaceDynamicTransformContContinue - ContinueFunctorType; + using ContinueFunctorType = + detail::FunctionInterfaceDynamicTransformContContinue; FunctionInterface emptyInterface; ContinueFunctorType continueFunctor = @@ -768,7 +767,7 @@ public: template VTKM_CONT void operator()(const T& newParameter) const { - typedef typename FunctionInterface::ComponentSig NewFSigComp; + using NewFSigComp = typename FunctionInterface::ComponentSig; //Determine if we should do the next transform using appended = brigand::push_back; @@ -788,11 +787,10 @@ public: template void DoNextTransform(vtkm::internal::FunctionInterface& nextInterface) const { - typedef FunctionInterfaceDynamicTransformContContinue - NextContinueType; + using NextContinueType = FunctionInterfaceDynamicTransformContContinue; NextContinueType nextContinue = NextContinueType(this->OriginalInterface, nextInterface, this->Transform, this->Finish); static const vtkm::IdComponent Index = @@ -806,11 +804,10 @@ private: void DoNextTransform(vtkm::internal::FunctionInterface& nextInterface, std::true_type) const { - typedef FunctionInterfaceDynamicTransformContContinue - NextContinueType; + using NextContinueType = FunctionInterfaceDynamicTransformContContinue; NextContinueType nextContinue = NextContinueType(this->OriginalInterface, nextInterface, this->Transform, this->Finish); static const vtkm::IdComponent Index = diff --git a/vtkm/internal/testing/UnitTestFunctionInterface.cxx b/vtkm/internal/testing/UnitTestFunctionInterface.cxx index 4dfe9a868..a4f9c1d99 100644 --- a/vtkm/internal/testing/UnitTestFunctionInterface.cxx +++ b/vtkm/internal/testing/UnitTestFunctionInterface.cxx @@ -35,19 +35,19 @@ namespace { -typedef vtkm::Id Type1; +using Type1 = vtkm::Id; const Type1 Arg1 = 1234; -typedef vtkm::Float64 Type2; +using Type2 = vtkm::Float64; const Type2 Arg2 = 5678.125; -typedef std::string Type3; +using Type3 = std::string; const Type3 Arg3("Third argument"); -typedef vtkm::Vec Type4; +using Type4 = vtkm::Vec; const Type4 Arg4(1.2f, 3.4f, 5.6f); -typedef vtkm::Id3 Type5; +using Type5 = vtkm::Id3; const Type5 Arg5(4, 5, 6); struct ThreeArgFunctor @@ -79,7 +79,7 @@ struct GetReferenceFunctor template struct ReturnType { - typedef const typename std::remove_reference::type* type; + using type = const typename std::remove_reference::type*; }; template @@ -94,7 +94,7 @@ struct PointerTransform template struct ReturnType { - typedef const T* type; + using type = const T*; }; template @@ -405,7 +405,7 @@ void TestStaticTransform() OriginalType funcInterface = vtkm::internal::make_FunctionInterface(Arg1, Arg2, Arg3); std::cout << "Transform with reported type." << std::endl; - typedef OriginalType::StaticTransformType::type ReportedType; + using ReportedType = OriginalType::StaticTransformType::type; ReportedType funcInterfaceTransform1 = funcInterface.StaticTransformCont(PointerTransform()); funcInterfaceTransform1.InvokeCont(ThreePointerArgFunctor()); funcInterfaceTransform1 = funcInterface.StaticTransformExec(PointerTransform()); @@ -500,7 +500,7 @@ void TestInvokeTime() vtkm::Float64 invokeCallTime = timer.GetElapsedTime(); std::cout << "Time for invoking function interface: " << invokeCallTime << " seconds" << std::endl; - std::cout << "Pointless result (makeing sure compiler computes it) " << f.Field << std::endl; + std::cout << "Pointless result (making sure compiler computes it) " << f.Field << std::endl; #if !defined(NDEBUG) && defined(VTKM_MSVC) // We expect function calls through the FunctionInterface class to take diff --git a/vtkm/interop/cuda/internal/TransferToOpenGL.h b/vtkm/interop/cuda/internal/TransferToOpenGL.h index 40c6405d0..94df9f427 100644 --- a/vtkm/interop/cuda/internal/TransferToOpenGL.h +++ b/vtkm/interop/cuda/internal/TransferToOpenGL.h @@ -131,7 +131,7 @@ private: template class TransferToOpenGL { - typedef vtkm::cont::DeviceAdapterTagCuda DeviceAdapterTag; + using DeviceAdapterTag = vtkm::cont::DeviceAdapterTagCuda; public: VTKM_CONT explicit TransferToOpenGL(BufferState& state) diff --git a/vtkm/interop/internal/BufferTypePicker.h b/vtkm/interop/internal/BufferTypePicker.h index 69a9010d9..64fc8f8e4 100644 --- a/vtkm/interop/internal/BufferTypePicker.h +++ b/vtkm/interop/internal/BufferTypePicker.h @@ -75,7 +75,7 @@ static inline VTKM_CONT GLenum BufferTypePicker(vtkm::UInt64) template static inline VTKM_CONT GLenum BufferTypePicker(T) { - typedef vtkm::TypeTraits Traits; + using Traits = vtkm::TypeTraits; return detail::BufferTypePickerImpl(typename Traits::NumericTag(), typename Traits::DimensionalityTag()); } diff --git a/vtkm/interop/internal/TransferToOpenGL.h b/vtkm/interop/internal/TransferToOpenGL.h index fa742cc9f..5de07d58e 100644 --- a/vtkm/interop/internal/TransferToOpenGL.h +++ b/vtkm/interop/internal/TransferToOpenGL.h @@ -214,7 +214,7 @@ public: //to openGL this works for all storage types. // //Second option is to call PrepareForInput and get a PortalConst in the - //exection environment. + //execution environment. //if we are StorageTagBasic this would allow us the ability to grab //the raw memory value and copy those, which we know are valid and remove //a unneeded copy. diff --git a/vtkm/interop/internal/testing/UnitTestBufferTypePicker.cxx b/vtkm/interop/internal/testing/UnitTestBufferTypePicker.cxx index 35670977f..ceb176a58 100644 --- a/vtkm/interop/internal/testing/UnitTestBufferTypePicker.cxx +++ b/vtkm/interop/internal/testing/UnitTestBufferTypePicker.cxx @@ -28,8 +28,8 @@ void TestBufferTypePicker() { //just verify that certain types match GLenum type; - typedef unsigned int vtkmUint; - typedef vtkm::FloatDefault T; + using vtkmUint = unsigned int; + using T = vtkm::FloatDefault; type = vtkm::interop::internal::BufferTypePicker(vtkm::Id()); VTKM_TEST_ASSERT(type == GL_ELEMENT_ARRAY_BUFFER, "Bad OpenGL Buffer Type"); diff --git a/vtkm/interop/testing/TestingOpenGLInterop.h b/vtkm/interop/testing/TestingOpenGLInterop.h index 8bbe47e2a..70dbc39a3 100644 --- a/vtkm/interop/testing/TestingOpenGLInterop.h +++ b/vtkm/interop/testing/TestingOpenGLInterop.h @@ -53,7 +53,7 @@ private: template static vtkm::cont::ArrayHandle FillArray(std::vector& data, std::size_t length) { - typedef typename std::vector::iterator iterator; + using iterator = typename std::vector::iterator; //make sure the data array is exactly the right length data.clear(); data.resize(length); @@ -177,7 +177,6 @@ private: template void operator()(const T t) const { - std::cout << "TransferFunctor" << std::endl; const std::size_t Size = 10; GLuint GLHandle; //verify that T is able to be transfer to openGL. @@ -197,7 +196,7 @@ private: //verify the results match what is in the array handle temp.SyncControlArray(); - T* expectedValues = temp.Internals->ControlArray.StealArray(); + T* expectedValues = temp.GetStorage().GetArray(); for (std::size_t i = 0; i < Size; ++i) { @@ -214,7 +213,7 @@ private: returnedValues = CopyGLBuffer(GLHandle, t); //verify the results match what is in the array handle temp.SyncControlArray(); - expectedValues = temp.Internals->ControlArray.StealArray(); + expectedValues = temp.GetStorage().GetArray(); for (std::size_t i = 0; i < Size * 2; ++i) { diff --git a/vtkm/interop/testing/UnitTestFancyTransferGLUT.cxx b/vtkm/interop/testing/UnitTestFancyTransferGLUT.cxx index 5c97052f7..0fc7c597e 100644 --- a/vtkm/interop/testing/UnitTestFancyTransferGLUT.cxx +++ b/vtkm/interop/testing/UnitTestFancyTransferGLUT.cxx @@ -40,7 +40,7 @@ // 1. Some Linux distributions default linker implicitly enables the as-needed // linking flag. This means that your shared library or executable will only // link to libraries from which they use symbols. So if you explicitly link to -// pthread but don't use any symbols you wont have a 'DT_NEEDED' entry for +// pthread but don't use any symbols you won't have a 'DT_NEEDED' entry for // pthread. // // 2. NVidia libGL (driver version 352 ) uses pthread but doesn't have diff --git a/vtkm/interop/testing/UnitTestTransferGLUT.cxx b/vtkm/interop/testing/UnitTestTransferGLUT.cxx index f8068b6a6..801d65929 100644 --- a/vtkm/interop/testing/UnitTestTransferGLUT.cxx +++ b/vtkm/interop/testing/UnitTestTransferGLUT.cxx @@ -42,7 +42,7 @@ // 1. Some Linux distributions default linker implicitly enables the as-needed // linking flag. This means that your shared library or executable will only // link to libraries from which they use symbols. So if you explicitly link to -// pthread but don't use any symbols you wont have a 'DT_NEEDED' entry for +// pthread but don't use any symbols you won't have a 'DT_NEEDED' entry for // pthread. // // 2. NVidia libGL (driver version 352 ) uses pthread but doesn't have diff --git a/vtkm/io/reader/BOVDataSetReader.h b/vtkm/io/reader/BOVDataSetReader.h index 370513a4d..4ec70566a 100644 --- a/vtkm/io/reader/BOVDataSetReader.h +++ b/vtkm/io/reader/BOVDataSetReader.h @@ -98,7 +98,7 @@ private: std::stringstream strStream(options); - //Format supports both space and "_" seperated tokens... + //Format supports both space and "_" separated tokens... if (token.find("DATA") != std::string::npos && token.find("FILE") != std::string::npos) { strStream >> bovFile >> std::ws; diff --git a/vtkm/rendering/AxisAnnotation3D.cxx b/vtkm/rendering/AxisAnnotation3D.cxx index 94a0b3913..5a762b8f5 100644 --- a/vtkm/rendering/AxisAnnotation3D.cxx +++ b/vtkm/rendering/AxisAnnotation3D.cxx @@ -159,6 +159,9 @@ void AxisAnnotation3D::Render(const Camera& camera, this->Labels[i]->SetPosition(vtkm::Float32(tickPos[0] - tickSize[0]), vtkm::Float32(tickPos[1] - tickSize[1]), vtkm::Float32(tickPos[2] - tickSize[2])); + vtkm::Vec pp(vtkm::Float32(tickPos[0] - tickSize[0]), + vtkm::Float32(tickPos[1] - tickSize[1]), + vtkm::Float32(tickPos[2] - tickSize[2])); this->Labels[i]->SetAlignment(TextAnnotation::HCenter, TextAnnotation::VCenter); } diff --git a/vtkm/rendering/CMakeLists.txt b/vtkm/rendering/CMakeLists.txt index c701c35e9..608e0562f 100644 --- a/vtkm/rendering/CMakeLists.txt +++ b/vtkm/rendering/CMakeLists.txt @@ -186,6 +186,7 @@ endif() #----------------------------------------------------------------------------- target_link_libraries(vtkm_rendering PUBLIC vtkm_cont) + if(UNIX AND NOT APPLE) target_link_libraries(vtkm_rendering PRIVATE rt ) endif() diff --git a/vtkm/rendering/Camera.h b/vtkm/rendering/Camera.h index c6dd27c3e..aea6b524d 100644 --- a/vtkm/rendering/Camera.h +++ b/vtkm/rendering/Camera.h @@ -438,7 +438,7 @@ public: /// \brief Rotate the camera about the view up vector centered at the focal point. /// /// Note that the view up vector is whatever was set via SetViewUp, and is - /// not necesarily perpendicular to the direction of projection. The angle is + /// not necessarily perpendicular to the direction of projection. The angle is /// given in degrees. /// /// Azimuth only makes sense for 3D cameras, so the camera mode will be set diff --git a/vtkm/rendering/Canvas.cxx b/vtkm/rendering/Canvas.cxx index 77e7db08b..d7ce07bc8 100644 --- a/vtkm/rendering/Canvas.cxx +++ b/vtkm/rendering/Canvas.cxx @@ -57,7 +57,7 @@ struct ClearBuffers : public vtkm::worklet::WorkletMapField color[3] = 0.f; // The depth is set to slightly larger than 1.0f, ensuring this color value always fails a // depth check - depth = 1.001f; + depth = VTKM_DEFAULT_CANVAS_DEPTH; } }; // struct ClearBuffers @@ -207,10 +207,12 @@ struct DrawColorBar : public vtkm::worklet::WorkletMapField { // local bar coord vtkm::Id x = index % BarWidth; - vtkm::Id y = index / BarWidth, yLocal = y; + vtkm::Id y = index / BarWidth; vtkm::Id sample = Horizontal ? x : y; vtkm::Vec color = colorMap.Get(sample); + vtkm::Float32 normalizedHeight = + Horizontal ? vtkm::Float32(y) / BarHeight : vtkm::Float32(x) / BarWidth; // offset to global image coord x += BarBottomLeft[0]; y += BarBottomLeft[1]; @@ -218,7 +220,6 @@ struct DrawColorBar : public vtkm::worklet::WorkletMapField vtkm::Id offset = y * ImageWidth + x; // If the colortable has alpha values, we blend each color sample with translucent white. // The height of the resultant translucent bar indicates the opacity. - vtkm::Float32 normalizedHeight = static_cast(yLocal) / BarHeight; if (color[3] < 1.0f && normalizedHeight <= color[3]) { vtkm::Float32 intensity = 0.4f; @@ -234,6 +235,8 @@ struct DrawColorBar : public vtkm::worklet::WorkletMapField } else { + // make sure this is opaque + color[3] = 1.f; frameBuffer.Set(offset, color); } } @@ -578,7 +581,8 @@ void Canvas::AddText(const vtkm::Matrix& transform, vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const + const std::string& text, + const vtkm::Float32& depth) const { if (!Internals->FontTexture.IsValid()) { @@ -590,7 +594,7 @@ void Canvas::AddText(const vtkm::Matrix& transform, vtkm::rendering::Canvas* self = const_cast(this); TextRenderer fontRenderer(self, Internals->Font, Internals->FontTexture); - fontRenderer.RenderText(transform, scale, anchor, color, text); + fontRenderer.RenderText(transform, scale, anchor, color, text, depth); } void Canvas::AddText(const vtkm::Vec& position, @@ -609,7 +613,7 @@ void Canvas::AddText(const vtkm::Vec& position, vtkm::Matrix transform = vtkm::MatrixMultiply(translationMatrix, vtkm::MatrixMultiply(scaleMatrix, rotationMatrix)); - this->AddText(transform, scale, anchor, color, text); + this->AddText(transform, scale, anchor, color, text, 0.f); } void Canvas::AddText(vtkm::Float32 x, diff --git a/vtkm/rendering/Canvas.h b/vtkm/rendering/Canvas.h index 96f9babe9..32e3f7b16 100644 --- a/vtkm/rendering/Canvas.h +++ b/vtkm/rendering/Canvas.h @@ -31,6 +31,8 @@ #include #include +#define VTKM_DEFAULT_CANVAS_DEPTH 1.001f + namespace vtkm { namespace rendering @@ -188,7 +190,8 @@ public: vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const; + const std::string& text, + const vtkm::Float32& depth = 0) const; friend class AxisAnnotation2D; diff --git a/vtkm/rendering/CanvasRayTracer.cxx b/vtkm/rendering/CanvasRayTracer.cxx index dc1640cc3..bd9c62015 100644 --- a/vtkm/rendering/CanvasRayTracer.cxx +++ b/vtkm/rendering/CanvasRayTracer.cxx @@ -68,7 +68,6 @@ public: { vtkm::Vec intersection = origin + inDepth * dir; vtkm::Vec point; - point[0] = static_cast(intersection[0]); point[1] = static_cast(intersection[1]); point[2] = static_cast(intersection[2]); @@ -91,18 +90,19 @@ public: // blend the mapped color with existing canvas color vtkm::Vec inColor = colorBuffer.Get(pixelIndex); - vtkm::Float32 alpha = inColor[3] * (1.f - color[3]); + // if transparency exists, all alphas have been pre-multiplied + vtkm::Float32 alpha = (1.f - color[3]); color[0] = color[0] + inColor[0] * alpha; color[1] = color[1] + inColor[1] * alpha; color[2] = color[2] + inColor[2] * alpha; - color[3] = alpha + color[3]; + color[3] = inColor[3] * alpha + color[3]; // clamp for (vtkm::Int32 i = 0; i < 4; ++i) { color[i] = vtkm::Min(1.f, vtkm::Max(color[i], 0.f)); } - // The existng depth should already been feed into thge ray mapper + // The existing depth should already been feed into the ray mapper // so no color contribution will exist past the existing depth. depthBuffer.Set(pixelIndex, depth); diff --git a/vtkm/rendering/ColorBarAnnotation.cxx b/vtkm/rendering/ColorBarAnnotation.cxx index 2422a4100..4b02eaee0 100644 --- a/vtkm/rendering/ColorBarAnnotation.cxx +++ b/vtkm/rendering/ColorBarAnnotation.cxx @@ -19,6 +19,7 @@ //============================================================================ #include +#include namespace vtkm { @@ -27,12 +28,32 @@ namespace rendering ColorBarAnnotation::ColorBarAnnotation() { + vtkm::Bounds bounds(vtkm::Range(-0.88, +0.88), vtkm::Range(+0.87, +0.92), vtkm::Range(0, 0)); + Position = bounds; + Horizontal = true; + FieldName = ""; } ColorBarAnnotation::~ColorBarAnnotation() { } +void ColorBarAnnotation::SetFieldName(const std::string& fieldName) +{ + FieldName = fieldName; +} + +void ColorBarAnnotation::SetPosition(const vtkm::Bounds& position) +{ + Position = position; + vtkm::Float64 x = Position.X.Length(); + vtkm::Float64 y = Position.Y.Length(); + if (x > y) + Horizontal = true; + else + Horizontal = false; +} + void ColorBarAnnotation::SetRange(const vtkm::Range& range, vtkm::IdComponent numTicks) { std::vector positions, proportions; @@ -52,17 +73,50 @@ void ColorBarAnnotation::Render(const vtkm::rendering::Camera& camera, const vtkm::rendering::WorldAnnotator& worldAnnotator, vtkm::rendering::Canvas& canvas) { - vtkm::Bounds bounds(vtkm::Range(-0.88, +0.88), vtkm::Range(+0.87, +0.92), vtkm::Range(0, 0)); - canvas.AddColorBar(bounds, this->ColorTable, true); + canvas.AddColorBar(Position, this->ColorTable, Horizontal); this->Axis.SetColor(canvas.GetForegroundColor()); this->Axis.SetLineWidth(1); - this->Axis.SetScreenPosition(bounds.X.Min, bounds.Y.Min, bounds.X.Max, bounds.Y.Min); - this->Axis.SetMajorTickSize(0, .02, 1.0); + + if (Horizontal) + { + this->Axis.SetScreenPosition(Position.X.Min, Position.Y.Min, Position.X.Max, Position.Y.Min); + this->Axis.SetLabelAlignment(TextAnnotation::HCenter, TextAnnotation::Top); + this->Axis.SetMajorTickSize(0, .02, 1.0); + } + else + { + this->Axis.SetScreenPosition(Position.X.Min, Position.Y.Min, Position.X.Min, Position.Y.Max); + this->Axis.SetLabelAlignment(TextAnnotation::Right, TextAnnotation::VCenter); + this->Axis.SetMajorTickSize(.02, 0.0, 1.0); + } + this->Axis.SetMinorTickSize(0, 0, 0); // no minor ticks - this->Axis.SetLabelAlignment(TextAnnotation::HCenter, TextAnnotation::Top); this->Axis.Render(camera, worldAnnotator, canvas); + + if (FieldName != "") + { + vtkm::Vec labelPos; + if (Horizontal) + { + labelPos[0] = vtkm::Float32(Position.X.Min); + labelPos[1] = vtkm::Float32(Position.Y.Max); + } + else + { + labelPos[0] = vtkm::Float32(Position.X.Min - 0.07); + labelPos[1] = vtkm::Float32(Position.Y.Max + 0.03); + } + + vtkm::rendering::TextAnnotationScreen var(FieldName, + canvas.GetForegroundColor(), + .045f, // font scale + labelPos, + 0.f); // rotation + + var.Render(camera, worldAnnotator, canvas); + } } } } // namespace vtkm::rendering diff --git a/vtkm/rendering/ColorBarAnnotation.h b/vtkm/rendering/ColorBarAnnotation.h index b4f6efa2e..33a68b5e5 100644 --- a/vtkm/rendering/ColorBarAnnotation.h +++ b/vtkm/rendering/ColorBarAnnotation.h @@ -38,6 +38,9 @@ class VTKM_RENDERING_EXPORT ColorBarAnnotation protected: vtkm::rendering::ColorTable ColorTable; vtkm::rendering::AxisAnnotation2D Axis; + vtkm::Bounds Position; + bool Horizontal; + std::string FieldName; public: ColorBarAnnotation(); @@ -50,14 +53,22 @@ public: this->ColorTable = colorTable; } + VTKM_CONT void SetRange(const vtkm::Range& range, vtkm::IdComponent numTicks); + VTKM_CONT + void SetFieldName(const std::string& fieldName); + VTKM_CONT void SetRange(vtkm::Float64 l, vtkm::Float64 h, vtkm::IdComponent numTicks) { this->SetRange(vtkm::Range(l, h), numTicks); } + + VTKM_CONT + void SetPosition(const vtkm::Bounds& position); + virtual void Render(const vtkm::rendering::Camera& camera, const vtkm::rendering::WorldAnnotator& worldAnnotator, vtkm::rendering::Canvas& canvas); diff --git a/vtkm/rendering/ColorTable.h b/vtkm/rendering/ColorTable.h index 1796892b0..d8ba4433a 100644 --- a/vtkm/rendering/ColorTable.h +++ b/vtkm/rendering/ColorTable.h @@ -41,7 +41,7 @@ struct ColorTableInternals; /// /// This class provides the basic representation of a color table. This class was /// Ported from EAVL. Originally created by Jeremy Meredith, Dave Pugmire, -/// and Sean Ahern. This class uses seperate RGB and alpha control points and can +/// and Sean Ahern. This class uses separate RGB and alpha control points and can /// be used as a transfer function. /// class VTKM_RENDERING_EXPORT ColorTable diff --git a/vtkm/rendering/ConnectivityProxy.cxx b/vtkm/rendering/ConnectivityProxy.cxx index 8e2105ab0..3e4714fc6 100644 --- a/vtkm/rendering/ConnectivityProxy.cxx +++ b/vtkm/rendering/ConnectivityProxy.cxx @@ -202,7 +202,7 @@ public: } else { - throw vtkm::cont::ErrorBadValue("ENGERY MODE Not implemented for this use case\n"); + throw vtkm::cont::ErrorBadValue("ENERGY MODE Not implemented for this use case\n"); } Tracer->Trace(rays); diff --git a/vtkm/rendering/DecodePNG.cxx b/vtkm/rendering/DecodePNG.cxx index 249270844..52121c82a 100644 --- a/vtkm/rendering/DecodePNG.cxx +++ b/vtkm/rendering/DecodePNG.cxx @@ -59,13 +59,13 @@ in_size: size of the input PNG file in bytes. convert_to_rgba32: optional parameter, true by default. Set to true to get the output in RGBA 32-bit (8 bit per channel) color format no matter what color type the original PNG image had. This gives predictable, - useable data from any random input PNG. + usable data from any random input PNG. Set to false to do no color conversion at all. The result then has the same data type as the PNG image, which can range from 1 bit to 64 bits per pixel. Information about the color type or palette colors are not provided. You need to know this information yourself to be able to use the data so this only works for trusted PNG files. Use LodePNG instead of picoPNG if you need this information. -return: 0 if success, not 0 if some error occured. +return: 0 if success, not 0 if some error occurred. */ int DecodePNG(std::vector& out_image, unsigned long& image_width, diff --git a/vtkm/rendering/LineRenderer.cxx b/vtkm/rendering/LineRenderer.cxx index 1bfb8ff65..c3f043080 100644 --- a/vtkm/rendering/LineRenderer.cxx +++ b/vtkm/rendering/LineRenderer.cxx @@ -65,21 +65,43 @@ void LineRenderer::RenderLine(const vtkm::Vec& point0, vtkm::Id dx = vtkm::Abs(x1 - x0), sx = x0 < x1 ? 1 : -1; vtkm::Id dy = -vtkm::Abs(y1 - y0), sy = y0 < y1 ? 1 : -1; vtkm::Id err = dx + dy, err2 = 0; - vtkm::rendering::Canvas::ColorBufferType::PortalControl colorPortal = + auto colorPortal = vtkm::rendering::Canvas::ColorBufferType(Canvas->GetColorBuffer()).GetPortalControl(); - vtkm::rendering::Canvas::DepthBufferType::PortalControl depthPortal = + auto depthPortal = vtkm::rendering::Canvas::DepthBufferType(Canvas->GetDepthBuffer()).GetPortalControl(); vtkm::Vec colorC = color.Components; + while (x0 >= 0 && x0 < Canvas->GetWidth() && y0 >= 0 && y0 < Canvas->GetHeight()) { vtkm::Float32 t = (dx == 0) ? 1.0f : (static_cast(x0) - p0[0]) / (p1[0] - p0[0]); + t = vtkm::Min(1.f, vtkm::Max(0.f, t)); vtkm::Float32 z = vtkm::Lerp(z0, z1, t); vtkm::Id index = y0 * Canvas->GetWidth() + x0; - if (depthPortal.Get(index) > z) + vtkm::Vec currentColor = colorPortal.Get(index); + vtkm::Float32 currentZ = depthPortal.Get(index); + bool blend = currentColor[3] < 1.f && z > currentZ; + if (currentZ > z || blend) { - depthPortal.Set(index, z); - colorPortal.Set(index, colorC); + vtkm::Vec writeColor = colorC; + vtkm::Float32 depth = z; + + if (blend) + { + // If there is any transparency, all alphas + // have been pre-mulitplied + vtkm::Float32 alpha = (1.f - currentColor[3]); + writeColor[0] = currentColor[0] + colorC[0] * alpha; + writeColor[1] = currentColor[1] + colorC[1] * alpha; + writeColor[2] = currentColor[2] + colorC[2] * alpha; + writeColor[3] = 1.f * alpha + currentColor[3]; // we are always drawing opaque lines + // keep the current z. Line z interpolation is not accurate + depth = currentZ; + } + + depthPortal.Set(index, depth); + colorPortal.Set(index, writeColor); } + if (x0 == x1 && y0 == y1) { break; diff --git a/vtkm/rendering/MapperGL.cxx b/vtkm/rendering/MapperGL.cxx index 1b7a44a12..7d5e0e0cc 100644 --- a/vtkm/rendering/MapperGL.cxx +++ b/vtkm/rendering/MapperGL.cxx @@ -459,17 +459,17 @@ void MapperGL::RenderCells(const vtkm::cont::DynamicCellSet& cellset, vtkm::cont::ArrayHandleUniformPointCoordinates uVerts; vtkm::cont::ArrayHandle> eVerts; - if (dcoords.IsSameType()) + if (dcoords.IsType()) { uVerts = dcoords.Cast(); RenderTriangles(*this, numTri, uVerts, indices, sf, colorTable, scalarRange, camera); } - else if (dcoords.IsSameType>>()) + else if (dcoords.IsType>>()) { eVerts = dcoords.Cast>>(); RenderTriangles(*this, numTri, eVerts, indices, sf, colorTable, scalarRange, camera); } - else if (dcoords.IsSameType, vtkm::cont::ArrayHandle, vtkm::cont::ArrayHandle>>()) diff --git a/vtkm/rendering/TextAnnotationBillboard.cxx b/vtkm/rendering/TextAnnotationBillboard.cxx index 76b0f4372..f6fb0ee11 100644 --- a/vtkm/rendering/TextAnnotationBillboard.cxx +++ b/vtkm/rendering/TextAnnotationBillboard.cxx @@ -69,7 +69,6 @@ void TextAnnotationBillboard::Render(const vtkm::rendering::Camera& camera, vtkm::MatrixMultiply(projectionMatrix, viewMatrix), this->Position); canvas.SetViewToScreenSpace(camera, true); - MatrixType translateMatrix = vtkm::Transform3DTranslate(screenPos[0], screenPos[1], -screenPos[2]); @@ -98,7 +97,10 @@ void TextAnnotationBillboard::Render(const vtkm::rendering::Camera& camera, VectorType right = vtkm::Transform3DVector(fullTransformMatrix, VectorType(1, 0, 0)); VectorType up = vtkm::Transform3DVector(fullTransformMatrix, VectorType(0, 1, 0)); - worldAnnotator.AddText(origin, right, up, this->Scale, this->Anchor, this->TextColor, this->Text); + // scale depth from (1, -1) to (0, 1); + vtkm::Float32 depth = screenPos[2] * .5f + .5f; + worldAnnotator.AddText( + origin, right, up, this->Scale, this->Anchor, this->TextColor, this->Text, depth); canvas.SetViewToWorldSpace(camera, true); } diff --git a/vtkm/rendering/TextRenderer.cxx b/vtkm/rendering/TextRenderer.cxx index 7033392dc..4365a234c 100644 --- a/vtkm/rendering/TextRenderer.cxx +++ b/vtkm/rendering/TextRenderer.cxx @@ -35,34 +35,43 @@ namespace internal struct RenderBitmapFont : public vtkm::worklet::WorkletMapField { using ColorBufferType = vtkm::rendering::Canvas::ColorBufferType; + using DepthBufferType = vtkm::rendering::Canvas::DepthBufferType; using FontTextureType = vtkm::rendering::Canvas::FontTextureType; - typedef void ControlSignature(FieldIn<>, FieldIn<>, ExecObject, WholeArrayInOut<>); - typedef void ExecutionSignature(_1, _2, _3, _4); + typedef void ControlSignature(FieldIn<>, + FieldIn<>, + ExecObject, + WholeArrayInOut<>, + WholeArrayInOut<>); + typedef void ExecutionSignature(_1, _2, _3, _4, _5); using InputDomain = _1; VTKM_CONT RenderBitmapFont() {} VTKM_CONT - RenderBitmapFont(const vtkm::Vec& color, vtkm::Id width, vtkm::Id height) + RenderBitmapFont(const vtkm::Vec& color, + vtkm::Id width, + vtkm::Id height, + vtkm::Float32 depth) : Color(color) , Width(width) , Height(height) + , Depth(depth) { } - template + template VTKM_EXEC void operator()(const vtkm::Vec& screenCoords, const vtkm::Vec& textureCoords, const FontTexture& fontTexture, - ColorBufferPortal& colorBuffer) const + ColorBufferPortal& colorBuffer, + DepthBufferPortal& depthBuffer) const { vtkm::Float32 x0 = Clamp(screenCoords[0], 0.0f, static_cast(Width - 1)); vtkm::Float32 x1 = Clamp(screenCoords[2], 0.0f, static_cast(Width - 1)); vtkm::Float32 y0 = Clamp(screenCoords[1], 0.0f, static_cast(Height - 1)); vtkm::Float32 y1 = Clamp(screenCoords[3], 0.0f, static_cast(Height - 1)); - // For crisp text rendering, we sample the font texture at points smaller than the pixel // sizes. Here we sample at increments of 0.25f, and scale the reported intensities accordingly vtkm::Float32 dx = x1 - x0, dy = y1 - y0; @@ -75,28 +84,43 @@ struct RenderBitmapFont : public vtkm::worklet::WorkletMapField vtkm::Float32 u = vtkm::Lerp(textureCoords[0], textureCoords[2], tu); vtkm::Float32 v = vtkm::Lerp(textureCoords[1], textureCoords[3], tv); vtkm::Float32 intensity = fontTexture.GetColor(u, v)[0] * 0.25f; - Plot(x, y, intensity, colorBuffer); + Plot(x, y, intensity, colorBuffer, depthBuffer); } } } - template + template VTKM_EXEC void Plot(vtkm::Float32 x, vtkm::Float32 y, vtkm::Float32 intensity, - ColorBufferPortal& colorBuffer) const + ColorBufferPortal& colorBuffer, + DepthBufferPortal& depthBuffer) const { vtkm::Id index = static_cast(vtkm::Round(y)) * Width + static_cast(vtkm::Round(x)); vtkm::Vec srcColor = colorBuffer.Get(index); + vtkm::Float32 currentDepth = depthBuffer.Get(index); + bool swap = Depth > currentDepth; + intensity = intensity * Color[3]; - vtkm::Float32 inverseIntensity = 1.0f - intensity; - vtkm::Float32 alpha = srcColor[3] * inverseIntensity; + vtkm::Vec color = intensity * Color; + color[3] = intensity; + vtkm::Vec front = color; + vtkm::Vec back = srcColor; + + if (swap) + { + front = srcColor; + back = color; + } + vtkm::Vec blendedColor; - blendedColor[0] = Color[0] * intensity + srcColor[0] * alpha; - blendedColor[1] = Color[1] * intensity + srcColor[1] * alpha; - blendedColor[2] = Color[2] * intensity + srcColor[2] * alpha; - blendedColor[3] = alpha + intensity; + vtkm::Float32 alpha = (1.f - front[3]); + blendedColor[0] = front[0] + back[0] * alpha; + blendedColor[1] = front[1] + back[1] * alpha; + blendedColor[2] = front[2] + back[2] * alpha; + blendedColor[3] = back[3] * alpha + front[3]; + colorBuffer.Set(index, blendedColor); } @@ -109,11 +133,13 @@ struct RenderBitmapFont : public vtkm::worklet::WorkletMapField vtkm::Vec Color; vtkm::Id Width; vtkm::Id Height; + vtkm::Float32 Depth; }; // struct RenderBitmapFont struct RenderBitmapFontExecutor { using ColorBufferType = vtkm::rendering::Canvas::ColorBufferType; + using DepthBufferType = vtkm::rendering::Canvas::DepthBufferType; using FontTextureType = vtkm::rendering::Canvas::FontTextureType; using ScreenCoordsArrayHandle = vtkm::cont::ArrayHandle>; using TextureCoordsArrayHandle = vtkm::cont::ArrayHandle>; @@ -124,13 +150,16 @@ struct RenderBitmapFontExecutor const FontTextureType& fontTexture, const vtkm::Vec& color, const ColorBufferType& colorBuffer, + const DepthBufferType& depthBuffer, vtkm::Id width, - vtkm::Id height) + vtkm::Id height, + vtkm::Float32 depth) : ScreenCoords(screenCoords) , TextureCoords(textureCoords) , FontTexture(fontTexture) , ColorBuffer(colorBuffer) - , Worklet(color, width, height) + , DepthBuffer(depthBuffer) + , Worklet(color, width, height, depth) { } @@ -141,7 +170,7 @@ struct RenderBitmapFontExecutor vtkm::worklet::DispatcherMapField dispatcher(Worklet); dispatcher.Invoke( - ScreenCoords, TextureCoords, FontTexture.GetExecObject(), ColorBuffer); + ScreenCoords, TextureCoords, FontTexture.GetExecObject(), ColorBuffer, DepthBuffer); return true; } @@ -149,6 +178,7 @@ struct RenderBitmapFontExecutor TextureCoordsArrayHandle TextureCoords; FontTextureType FontTexture; ColorBufferType ColorBuffer; + DepthBufferType DepthBuffer; RenderBitmapFont Worklet; }; // struct RenderBitmapFontExecutor } // namespace internal @@ -201,7 +231,8 @@ void TextRenderer::RenderText(const vtkm::Matrix& transform vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) + const std::string& text, + const vtkm::Float32& depth) { vtkm::Float32 textWidth = this->Font.GetTextWidth(text); vtkm::Float32 fx = -(0.5f + 0.5f * anchor[0]) * textWidth; @@ -246,8 +277,10 @@ void TextRenderer::RenderText(const vtkm::Matrix& transform FontTexture, color.Components, Canvas->GetColorBuffer(), + Canvas->GetDepthBuffer(), Canvas->GetWidth(), - Canvas->GetHeight())); + Canvas->GetHeight(), + depth)); } } } // namespace vtkm::rendering diff --git a/vtkm/rendering/TextRenderer.h b/vtkm/rendering/TextRenderer.h index 1b745ff24..05d0ad1d0 100644 --- a/vtkm/rendering/TextRenderer.h +++ b/vtkm/rendering/TextRenderer.h @@ -64,7 +64,8 @@ public: vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text); + const std::string& text, + const vtkm::Float32& depth = 0.f); private: const vtkm::rendering::Canvas* Canvas; diff --git a/vtkm/rendering/Triangulator.h b/vtkm/rendering/Triangulator.h index cb3fa7376..4225172fd 100644 --- a/vtkm/rendering/Triangulator.h +++ b/vtkm/rendering/Triangulator.h @@ -293,7 +293,7 @@ public: { if (index == 0) return; - //if we are a shared face, mark ourself and neighbor for desctruction + //if we are a shared face, mark ourself and neighbor for destruction if (IsTwin(indices.Get(index), indices.Get(index - 1))) { outputFlags.Set(index, 0); diff --git a/vtkm/rendering/View2D.cxx b/vtkm/rendering/View2D.cxx index ee9fa739d..a27de288c 100644 --- a/vtkm/rendering/View2D.cxx +++ b/vtkm/rendering/View2D.cxx @@ -102,6 +102,7 @@ void View2D::RenderScreenAnnotations() if (scene.GetNumberOfActors() > 0) { //this->ColorBarAnnotation.SetAxisColor(vtkm::rendering::Color(1,1,1)); + this->ColorBarAnnotation.SetFieldName(scene.GetActor(0).GetScalarField().GetName()); this->ColorBarAnnotation.SetRange( scene.GetActor(0).GetScalarRange().Min, scene.GetActor(0).GetScalarRange().Max, 5); this->ColorBarAnnotation.SetColorTable(scene.GetActor(0).GetColorTable()); diff --git a/vtkm/rendering/View3D.cxx b/vtkm/rendering/View3D.cxx index b195b6343..f9e16c943 100644 --- a/vtkm/rendering/View3D.cxx +++ b/vtkm/rendering/View3D.cxx @@ -69,6 +69,7 @@ void View3D::RenderScreenAnnotations() if (this->GetScene().GetNumberOfActors() > 0) { //this->ColorBarAnnotation.SetAxisColor(vtkm::rendering::Color(1,1,1)); + this->ColorBarAnnotation.SetFieldName(this->GetScene().GetActor(0).GetScalarField().GetName()); this->ColorBarAnnotation.SetRange(this->GetScene().GetActor(0).GetScalarRange(), 5); this->ColorBarAnnotation.SetColorTable(this->GetScene().GetActor(0).GetColorTable()); this->ColorBarAnnotation.Render( diff --git a/vtkm/rendering/WorldAnnotator.cxx b/vtkm/rendering/WorldAnnotator.cxx index 008e26b65..6bb881495 100644 --- a/vtkm/rendering/WorldAnnotator.cxx +++ b/vtkm/rendering/WorldAnnotator.cxx @@ -54,7 +54,8 @@ void WorldAnnotator::AddText(const vtkm::Vec& origin, vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const + const std::string& text, + const vtkm::Float32 depth) const { vtkm::Vec n = vtkm::Cross(right, up); vtkm::Normalize(n); @@ -62,7 +63,7 @@ void WorldAnnotator::AddText(const vtkm::Vec& origin, vtkm::Matrix transform = MatrixHelpers::WorldMatrix(origin, right, up, n); transform = vtkm::MatrixMultiply(Canvas->GetModelView(), transform); transform = vtkm::MatrixMultiply(Canvas->GetProjection(), transform); - Canvas->AddText(transform, scale, anchor, color, text); + Canvas->AddText(transform, scale, anchor, color, text, depth); } } } // namespace vtkm::rendering diff --git a/vtkm/rendering/WorldAnnotator.h b/vtkm/rendering/WorldAnnotator.h index 042fcf48c..63fc4faaa 100644 --- a/vtkm/rendering/WorldAnnotator.h +++ b/vtkm/rendering/WorldAnnotator.h @@ -67,7 +67,8 @@ public: vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const; + const std::string& text, + const vtkm::Float32 depth = 0.f) const; VTKM_CONT void AddText(vtkm::Float32 originX, diff --git a/vtkm/rendering/WorldAnnotatorGL.cxx b/vtkm/rendering/WorldAnnotatorGL.cxx index 20fc51e16..c569c9775 100644 --- a/vtkm/rendering/WorldAnnotatorGL.cxx +++ b/vtkm/rendering/WorldAnnotatorGL.cxx @@ -78,7 +78,8 @@ void WorldAnnotatorGL::AddText(const vtkm::Vec& origin, vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const + const std::string& text, + const vtkm::Float32 vtkmNotUsed(depth)) const { vtkm::Vec n = vtkm::Cross(right, up); diff --git a/vtkm/rendering/WorldAnnotatorGL.h b/vtkm/rendering/WorldAnnotatorGL.h index 6dd5b5ec8..3b72c1c30 100644 --- a/vtkm/rendering/WorldAnnotatorGL.h +++ b/vtkm/rendering/WorldAnnotatorGL.h @@ -50,7 +50,8 @@ public: vtkm::Float32 scale, const vtkm::Vec& anchor, const vtkm::rendering::Color& color, - const std::string& text) const override; + const std::string& text, + const vtkm::Float32 depth = 0.f) const override; private: BitmapFont Font; diff --git a/vtkm/rendering/raytracing/ChannelBuffer.h b/vtkm/rendering/raytracing/ChannelBuffer.h index 942f059d7..e8d13ea3b 100644 --- a/vtkm/rendering/raytracing/ChannelBuffer.h +++ b/vtkm/rendering/raytracing/ChannelBuffer.h @@ -40,8 +40,8 @@ namespace raytracing /// \c The ChannelBuffer class is meant to handle a buffer of values with potentially many /// channels. While RGBA values could be placed in a Vec, data with a large number of /// channels (e.g., 100+ energy bins) are better handled by a raw array. Rays can have color, -/// absorption, absorption + emmision, or even track additional scalar values to support -/// standards such as Cinema. This class allows us to treat all of these differnt use cases +/// absorption, absorption + emission, or even track additional scalar values to support +/// standards such as Cinema. This class allows us to treat all of these different use cases /// with the same type. /// /// This class has methods that can be utilized by other VTK-m classes that already have a diff --git a/vtkm/rendering/raytracing/ConnectivityBase.h b/vtkm/rendering/raytracing/ConnectivityBase.h index 5df12ef77..405553223 100644 --- a/vtkm/rendering/raytracing/ConnectivityBase.h +++ b/vtkm/rendering/raytracing/ConnectivityBase.h @@ -50,7 +50,7 @@ public: virtual void SetVolumeData(const vtkm::cont::Field& scalarField, const vtkm::Range& scalarBounds) = 0; - virtual void SetEnergyData(const vtkm::cont::Field& absorbtion, + virtual void SetEnergyData(const vtkm::cont::Field& absorption, const vtkm::Int32 numBins, const vtkm::cont::Field& emission = vtkm::cont::Field()) = 0; diff --git a/vtkm/rendering/raytracing/ConnectivityTracer.h b/vtkm/rendering/raytracing/ConnectivityTracer.h index 32701cc73..bdcb32785 100644 --- a/vtkm/rendering/raytracing/ConnectivityTracer.h +++ b/vtkm/rendering/raytracing/ConnectivityTracer.h @@ -48,7 +48,7 @@ struct RenderFunctor; // // Ray tracker manages memory and pointer -// swaping for current cell intersection data +// swapping for current cell intersection data // template class RayTracking diff --git a/vtkm/rendering/raytracing/ConnectivityTracer.hxx b/vtkm/rendering/raytracing/ConnectivityTracer.hxx index 61980cc28..ace9d52aa 100644 --- a/vtkm/rendering/raytracing/ConnectivityTracer.hxx +++ b/vtkm/rendering/raytracing/ConnectivityTracer.hxx @@ -559,15 +559,15 @@ public: // // Traditionally, we would only keep track of a single intensity value per ray - // per bin and we would integrate from the begining to end of the ray. In a + // per bin and we would integrate from the beginning to end of the ray. In a // distributed memory setting, we would move cell data around so that the // entire ray could be traced, but in situ, moving that much cell data around // could blow memory. Here we are keeping track of two values. Total absorption - // through this contigious segment of the mesh, and the amount of emissed engery + // through this contiguous segment of the mesh, and the amount of emitted energy // that makes it out of this mesh segment. If this is really run on a single node, // we can get the final energy value by multiplying the background intensity by - // the total absorption of the mesh segment and add in the amount of emissed - // enegery that escapes. + // the total absorption of the mesh segment and add in the amount of emitted + // energy that escapes. // FloatType absorbIntensity = static_cast(absorptionBins.Get(rayOffset + i)); FloatType emissionIntensity = static_cast(emissionBins.Get(rayOffset + i)); @@ -1013,9 +1013,9 @@ void ConnectivityTracer::SampleCells( detail::RayTracking& tracker, Device) { - using SamplePoints = + using SampleP = SampleCellAssocPoints>; - using SampleCells = + using SampleC = SampleCellAssocCells>; vtkm::cont::Timer timer; @@ -1023,13 +1023,13 @@ void ConnectivityTracer::SampleCells( if (FieldAssocPoints) { - vtkm::worklet::DispatcherMapField( - SamplePoints(this->SampleDistance, - vtkm::Float32(this->ScalarBounds.Min), - vtkm::Float32(this->ScalarBounds.Max), - this->ColorMap, - rays.Buffers.at(0).Buffer, - this->MeshConn)) + vtkm::worklet::DispatcherMapField( + SampleP(this->SampleDistance, + vtkm::Float32(this->ScalarBounds.Min), + vtkm::Float32(this->ScalarBounds.Max), + this->ColorMap, + rays.Buffers.at(0).Buffer, + this->MeshConn)) .Invoke(rays.HitIdx, this->MeshConn.GetCoordinates(), this->ScalarField.GetData(), @@ -1042,13 +1042,13 @@ void ConnectivityTracer::SampleCells( } else { - vtkm::worklet::DispatcherMapField( - SampleCells(this->SampleDistance, - vtkm::Float32(this->ScalarBounds.Min), - vtkm::Float32(this->ScalarBounds.Max), - this->ColorMap, - rays.Buffers.at(0).Buffer, - this->MeshConn)) + vtkm::worklet::DispatcherMapField( + SampleC(this->SampleDistance, + vtkm::Float32(this->ScalarBounds.Min), + vtkm::Float32(this->ScalarBounds.Max), + this->ColorMap, + rays.Buffers.at(0).Buffer, + this->MeshConn)) .Invoke(rays.HitIdx, this->ScalarField.GetData(), *(tracker.EnterDist), @@ -1181,7 +1181,7 @@ void ConnectivityTracer::RenderOnDevice(Ray entryTimer; // - // if ray misses the exteral face it will be marked RAY_EXITED_MESH + // if ray misses the external face it will be marked RAY_EXITED_MESH // MeshConn.FindEntry(rays, Device()); MeshEntryTime += entryTimer.GetElapsedTime(); @@ -1238,7 +1238,7 @@ void ConnectivityTracer::RenderOnDevice(Ray inverseExtent; inverseExtent[0] = 1.f / (BoundingBox[1] - BoundingBox[0]); inverseExtent[1] = 1.f / (BoundingBox[3] - BoundingBox[2]); diff --git a/vtkm/rendering/raytracing/MeshConnectivityStructures.h b/vtkm/rendering/raytracing/MeshConnectivityStructures.h index 45c3d7cba..23341bd80 100644 --- a/vtkm/rendering/raytracing/MeshConnectivityStructures.h +++ b/vtkm/rendering/raytracing/MeshConnectivityStructures.h @@ -65,7 +65,7 @@ public: IdHandle CellConn; IdHandle CellOffsets; UCharHandle Shapes; - // Mesh Boundry + // Mesh Boundary Id4Handle ExternalTriangles; LinearBVH Bvh; @@ -304,7 +304,7 @@ public: IdHandle FaceConnectivity; CountingHandle CellOffsets; IdHandle CellConnectivity; - // Mesh Boundry + // Mesh Boundary LinearBVH Bvh; Id4Handle ExternalTriangles; @@ -547,7 +547,7 @@ public: vtkm::Bounds CoordinateBounds; vtkm::cont::CoordinateSystem Coords; vtkm::cont::CellSetStructured<3> Cellset; - // Mesh Boundry + // Mesh Boundary LinearBVH Bvh; Id4Handle ExternalTriangles; diff --git a/vtkm/rendering/raytracing/MortonCodes.h b/vtkm/rendering/raytracing/MortonCodes.h index 66b26d530..9fd93fd48 100644 --- a/vtkm/rendering/raytracing/MortonCodes.h +++ b/vtkm/rendering/raytracing/MortonCodes.h @@ -207,7 +207,7 @@ public: vtkm::Vec cellFace; cellFace[0] = cellId; - // We must be sure that this calulation is the same for all faces. If we didn't + // We must be sure that this calculation is the same for all faces. If we didn't // then it is possible for the same face to end up in multiple morton "buckets" due to // the wonders of floating point math. This is bad. If we calculate in the same order // for all faces, then at worst, two different faces can enter the same bucket, which diff --git a/vtkm/rendering/raytracing/RayOperations.h b/vtkm/rendering/raytracing/RayOperations.h index 5be33c6d0..1475e1574 100644 --- a/vtkm/rendering/raytracing/RayOperations.h +++ b/vtkm/rendering/raytracing/RayOperations.h @@ -209,7 +209,7 @@ public: .Invoke(rays.Status, masks); // - // Make empty composite vectors so we dont use up extra storage + // Make empty composite vectors so we don't use up extra storage // vtkm::IdComponent inComp[3]; inComp[0] = 0; diff --git a/vtkm/rendering/raytracing/VolumeRendererStructured.cxx b/vtkm/rendering/raytracing/VolumeRendererStructured.cxx index 0531d8fdf..7d9ef931a 100644 --- a/vtkm/rendering/raytracing/VolumeRendererStructured.cxx +++ b/vtkm/rendering/raytracing/VolumeRendererStructured.cxx @@ -134,7 +134,7 @@ public: { // // When searching for points, we consider the max value of the cell - // to be apart of the next cell. If the point falls on the boundry of the + // to be apart of the next cell. If the point falls on the boundary of the // data set, then it is technically inside a cell. This checks for that case // if (point[dim] == MaxPoint[dim]) @@ -340,16 +340,18 @@ public: InverseDeltaScalar = minScalar; } typedef void ControlSignature(FieldIn<>, + FieldIn<>, FieldIn<>, FieldIn<>, WholeArrayInOut<>, WholeArrayIn); - typedef void ExecutionSignature(_1, _2, _3, _4, _5, WorkIndex); + typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); template VTKM_EXEC void operator()(const vtkm::Vec& rayDir, const vtkm::Vec& rayOrigin, const vtkm::Float32& minDistance, + const vtkm::Float32& maxDistance, ColorBufferType& colorBuffer, ScalarPortalType& scalars, const vtkm::Id& pixelIndex) const @@ -370,7 +372,17 @@ public: } //get the initial sample position; vtkm::Vec sampleLocation; - sampleLocation = rayOrigin + (0.0001f + minDistance) * rayDir; + // find the distance to the first sample + vtkm::Float32 distance = minDistance + 0.0001f; + sampleLocation = rayOrigin + distance * rayDir; + // since the calculations are slightly different, we could hit an + // edge case where the first sample location may not be in the data set. + // Thus, advance to the next sample location + while (!Locator.IsInside(sampleLocation) && distance < maxDistance) + { + distance += SampleDistance; + sampleLocation = rayOrigin + distance * rayDir; + } /* 7----------6 /| /| @@ -399,7 +411,7 @@ public: vtkm::Vec invSpacing(0.f, 0.f, 0.f); - while (Locator.IsInside(sampleLocation)) + while (Locator.IsInside(sampleLocation) && distance < maxDistance) { vtkm::Float32 mint = vtkm::Min(tx, vtkm::Min(ty, tz)); vtkm::Float32 maxt = vtkm::Max(tx, vtkm::Max(ty, tz)); @@ -464,6 +476,7 @@ public: color[2] = color[2] + sampleColor[2] * sampleColor[3]; color[3] = sampleColor[3] + color[3]; //advance + distance += SampleDistance; sampleLocation = sampleLocation + SampleDistance * rayDir; //this is linear could just do an addition @@ -523,16 +536,18 @@ public: InverseDeltaScalar = minScalar; } typedef void ControlSignature(FieldIn<>, + FieldIn<>, FieldIn<>, FieldIn<>, WholeArrayInOut<>, WholeArrayIn); - typedef void ExecutionSignature(_1, _2, _3, _4, _5, WorkIndex); + typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); template VTKM_EXEC void operator()(const vtkm::Vec& rayDir, const vtkm::Vec& rayOrigin, const vtkm::Float32& minDistance, + const vtkm::Float32& maxDistance, ColorBufferType& colorBuffer, const ScalarPortalType& scalars, const vtkm::Id& pixelIndex) const @@ -551,7 +566,17 @@ public: return; //TODO: Compact? or just image subset... //get the initial sample position; vtkm::Vec sampleLocation; - sampleLocation = rayOrigin + (0.0001f + minDistance) * rayDir; + // find the distance to the first sample + vtkm::Float32 distance = minDistance + 0.0001f; + sampleLocation = rayOrigin + distance * rayDir; + // since the calculations are slightly different, we could hit an + // edge case where the first sample location may not be in the data set. + // Thus, advance to the next sample location + while (!Locator.IsInside(sampleLocation) && distance < maxDistance) + { + distance += SampleDistance; + sampleLocation = rayOrigin + distance * rayDir; + } /* 7----------6 @@ -571,7 +596,7 @@ public: vtkm::Vec bottomLeft(0.f, 0.f, 0.f); vtkm::Vec invSpacing(0.f, 0.f, 0.f); vtkm::Vec cell(0, 0, 0); - while (Locator.IsInside(sampleLocation)) + while (Locator.IsInside(sampleLocation) && distance < maxDistance) { vtkm::Float32 mint = vtkm::Min(tx, vtkm::Min(ty, tz)); vtkm::Float32 maxt = vtkm::Max(tx, vtkm::Max(ty, tz)); @@ -605,6 +630,7 @@ public: color[2] = color[2] + sampleColor[2] * alpha; color[3] = alpha + color[3]; //advance + distance += SampleDistance; sampleLocation = sampleLocation + SampleDistance * rayDir; if (color[3] >= 1.f) @@ -690,7 +716,7 @@ public: minDistance = vtkm::Max( vtkm::Max(vtkm::Max(vtkm::Min(ymin, ymax), vtkm::Min(xmin, xmax)), vtkm::Min(zmin, zmax)), - 0.f); + minDistance); vtkm::Float32 exitDistance = vtkm::Min(vtkm::Min(vtkm::Max(ymin, ymax), vtkm::Max(xmin, xmax)), vtkm::Max(zmin, zmax)); maxDistance = vtkm::Min(maxDistance, exitDistance); @@ -723,7 +749,7 @@ void VolumeRendererStructured::SetData(const vtkm::cont::CoordinateSystem& coord const vtkm::cont::CellSetStructured<3>& cellset, const vtkm::Range& scalarRange) { - if (coords.GetData().IsSameType()) + if (coords.GetData().IsSameType(CartesianArrayHandle())) IsUniformDataSet = false; IsSceneDirty = true; SpatialExtent = coords.GetBounds(); @@ -819,7 +845,12 @@ void VolumeRendererStructured::RenderOnDevice(vtkm::rendering::raytracing::Ray

::type::value), "Trying to compare a scalar with a vector."); - // Do all comparisions using 64-bit floats. + // Do all comparisons using 64-bit floats. vtkm::Float64 value1 = vtkm::Float64(scalar1); vtkm::Float64 value2 = vtkm::Float64(scalar2); diff --git a/vtkm/testing/TestingMath.h b/vtkm/testing/TestingMath.h index 5e8a557e4..a3f7a70d8 100644 --- a/vtkm/testing/TestingMath.h +++ b/vtkm/testing/TestingMath.h @@ -332,8 +332,8 @@ struct TryScalarFieldTests template struct ScalarVectorFieldTests : public vtkm::exec::FunctorBase { - typedef vtkm::VecTraits Traits; - typedef typename Traits::ComponentType ComponentType; + using Traits = vtkm::VecTraits; + using ComponentType = typename Traits::ComponentType; enum { NUM_COMPONENTS = Traits::NUM_COMPONENTS @@ -696,7 +696,7 @@ struct AllTypesTests : public vtkm::exec::FunctorBase VTKM_MATH_ASSERT(test_equal(vtkm::Max(low, high), high), "Wrong max."); VTKM_MATH_ASSERT(test_equal(vtkm::Max(high, low), high), "Wrong max."); - typedef vtkm::VecTraits Traits; + using Traits = vtkm::VecTraits; T mixed1 = low; T mixed2 = high; Traits::SetComponent(mixed1, 0, Traits::GetComponent(high, 0)); diff --git a/vtkm/testing/UnitTestBounds.cxx b/vtkm/testing/UnitTestBounds.cxx index 52bc76f46..1cab9dc36 100644 --- a/vtkm/testing/UnitTestBounds.cxx +++ b/vtkm/testing/UnitTestBounds.cxx @@ -27,12 +27,19 @@ namespace void TestBounds() { - typedef vtkm::Vec Vec3; + using Vec3 = vtkm::Vec; std::cout << "Empty bounds." << std::endl; vtkm::Bounds emptyBounds; VTKM_TEST_ASSERT(!emptyBounds.IsNonEmpty(), "Non empty bounds not empty."); + vtkm::Bounds emptyBounds2; + VTKM_TEST_ASSERT(!emptyBounds2.IsNonEmpty(), "2nd empty bounds not empty."); + VTKM_TEST_ASSERT(!emptyBounds.Union(emptyBounds2).IsNonEmpty(), + "Union of empty bounds not empty."); + emptyBounds2.Include(emptyBounds); + VTKM_TEST_ASSERT(!emptyBounds2.IsNonEmpty(), "Include empty in empty is not empty."); + std::cout << "Single value bounds." << std::endl; vtkm::Bounds singleValueBounds(1.0, 1.0, 2.0, 2.0, 3.0, 3.0); VTKM_TEST_ASSERT(singleValueBounds.IsNonEmpty(), "Empty?"); diff --git a/vtkm/testing/UnitTestMatrix.cxx b/vtkm/testing/UnitTestMatrix.cxx index 851f16012..249157fe4 100644 --- a/vtkm/testing/UnitTestMatrix.cxx +++ b/vtkm/testing/UnitTestMatrix.cxx @@ -33,7 +33,7 @@ vtkm::Matrix TestValue(vtkm::Id index, const vtkm::Matrix value; for (vtkm::IdComponent rowIndex = 0; rowIndex < NumRow; rowIndex++) { - typedef vtkm::Vec RowType; + using RowType = vtkm::Vec; RowType row = TestValue(index, RowType()) + RowType(static_cast(10 * rowIndex)); vtkm::MatrixSetRow(value, rowIndex, row); @@ -53,8 +53,8 @@ struct MatrixTest { static const vtkm::IdComponent NUM_ROWS = NumRow; static const vtkm::IdComponent NUM_COLS = NumCol; - typedef vtkm::Matrix MatrixType; - typedef typename MatrixType::ComponentType ComponentType; + using MatrixType = vtkm::Matrix; + using ComponentType = typename MatrixType::ComponentType; static void BasicCreation() { @@ -74,18 +74,18 @@ struct MatrixTest FOR_ROW_COL(matrix) { matrix[row][col] = ComponentType(value(row, col) * 2); } FOR_ROW_COL(matrix) { - VTKM_TEST_ASSERT(test_equal(matrix(row, col), value(row, col) * 2), "Bad set or retreive."); + VTKM_TEST_ASSERT(test_equal(matrix(row, col), value(row, col) * 2), "Bad set or retrieve."); const MatrixType const_matrix = matrix; VTKM_TEST_ASSERT(test_equal(const_matrix(row, col), value(row, col) * 2), - "Bad set or retreive."); + "Bad set or retrieve."); } FOR_ROW_COL(matrix) { matrix(row, col) = value(row, col); } const MatrixType const_matrix = matrix; FOR_ROW_COL(matrix) { - VTKM_TEST_ASSERT(test_equal(matrix[row][col], value(row, col)), "Bad set or retreive."); - VTKM_TEST_ASSERT(test_equal(const_matrix[row][col], value(row, col)), "Bad set or retreive."); + VTKM_TEST_ASSERT(test_equal(matrix[row][col], value(row, col)), "Bad set or retrieve."); + VTKM_TEST_ASSERT(test_equal(const_matrix[row][col], value(row, col)), "Bad set or retrieve."); } VTKM_TEST_ASSERT(matrix == const_matrix, "Equal test operator not working."); VTKM_TEST_ASSERT(!(matrix != const_matrix), "Not-Equal test operator not working."); @@ -94,8 +94,8 @@ struct MatrixTest static void RowColAccessors() { - typedef vtkm::Vec ColumnType; - typedef vtkm::Vec RowType; + using ColumnType = vtkm::Vec; + using RowType = vtkm::Vec; const MatrixType const_matrix = TestValue(0, MatrixType()); MatrixType matrix; @@ -373,7 +373,7 @@ template struct SquareMatrixTest { static const vtkm::IdComponent SIZE = Size; - typedef vtkm::Matrix MatrixType; + using MatrixType = vtkm::Matrix; static void CheckMatrixSize() { @@ -582,7 +582,7 @@ struct VectorMultFunctor // This is mostly to make sure the compile can convert from Tuples // to vectors. const int SIZE = vtkm::VecTraits::NUM_COMPONENTS; - typedef typename vtkm::VecTraits::ComponentType ComponentType; + using ComponentType = typename vtkm::VecTraits::ComponentType; vtkm::Matrix matrix(0); VectorType inVec; diff --git a/vtkm/testing/UnitTestNewtonsMethod.cxx b/vtkm/testing/UnitTestNewtonsMethod.cxx index 3c7f6c721..72087fc7b 100644 --- a/vtkm/testing/UnitTestNewtonsMethod.cxx +++ b/vtkm/testing/UnitTestNewtonsMethod.cxx @@ -36,7 +36,7 @@ namespace template struct EvaluateFunctions { - typedef vtkm::Vec Vector3; + using Vector3 = vtkm::Vec; VTKM_EXEC_CONT Vector3 operator()(Vector3 x) const @@ -51,8 +51,8 @@ struct EvaluateFunctions template struct EvaluateJacobian { - typedef vtkm::Vec Vector3; - typedef vtkm::Matrix Matrix3x3; + using Vector3 = vtkm::Vec; + using Matrix3x3 = vtkm::Matrix; VTKM_EXEC_CONT Matrix3x3 operator()(Vector3 x) const @@ -76,7 +76,7 @@ void TestNewtonsMethodTemplate() { std::cout << "Testing Newton's Method." << std::endl; - typedef vtkm::Vec Vector3; + using Vector3 = vtkm::Vec; Vector3 desiredOutput(1, 1, 1); Vector3 expected1(2.0f / 3.0f, -1.0f / 3.0f, -2.0f / 3.0f); diff --git a/vtkm/testing/UnitTestRange.cxx b/vtkm/testing/UnitTestRange.cxx index 1238ca541..c2e16b37f 100644 --- a/vtkm/testing/UnitTestRange.cxx +++ b/vtkm/testing/UnitTestRange.cxx @@ -32,6 +32,12 @@ void TestRange() VTKM_TEST_ASSERT(!emptyRange.IsNonEmpty(), "Non empty range not empty."); VTKM_TEST_ASSERT(test_equal(emptyRange.Length(), 0.0), "Bad length."); + vtkm::Range emptyRange2; + VTKM_TEST_ASSERT(!emptyRange2.IsNonEmpty(), "2nd empty range not empty."); + VTKM_TEST_ASSERT(!emptyRange.Union(emptyRange2).IsNonEmpty(), "Union of empty ranges not empty."); + emptyRange2.Include(emptyRange); + VTKM_TEST_ASSERT(!emptyRange2.IsNonEmpty(), "Include empty in empty is not empty."); + std::cout << "Single value range." << std::endl; vtkm::Range singleValueRange(5.0, 5.0); VTKM_TEST_ASSERT(singleValueRange.IsNonEmpty(), "Empty?"); diff --git a/vtkm/testing/UnitTestTransform3D.cxx b/vtkm/testing/UnitTestTransform3D.cxx index 73c7f14ba..70303ff1a 100644 --- a/vtkm/testing/UnitTestTransform3D.cxx +++ b/vtkm/testing/UnitTestTransform3D.cxx @@ -43,8 +43,8 @@ struct TransformTests T RandomNum() { return this->RandomDistribution(g_RandomGenerator); } - typedef vtkm::Vec Vec; - typedef vtkm::Matrix Transform; + using Vec = vtkm::Vec; + using Transform = vtkm::Matrix; Vec RandomVector() { @@ -73,7 +73,7 @@ struct TransformTests VTKM_TEST_ASSERT(test_equal(translated2, startPoint + T(2) * translateAmount), "Bad translation."); - // Vectors should be invarient to translation. + // Vectors should be invariant to translation. translated1 = vtkm::Transform3DVector(translate, startPoint); std::cout << " Translated vector: " << translated1 << std::endl; VTKM_TEST_ASSERT(test_equal(translated1, startPoint), "Bad translation."); diff --git a/vtkm/testing/UnitTestTypeListTag.cxx b/vtkm/testing/UnitTestTypeListTag.cxx index 5dd0c264b..979066152 100644 --- a/vtkm/testing/UnitTestTypeListTag.cxx +++ b/vtkm/testing/UnitTestTypeListTag.cxx @@ -32,7 +32,7 @@ namespace class TypeSet { - typedef std::set NameSetType; + using NameSetType = std::set; NameSetType NameSet; public: diff --git a/vtkm/testing/UnitTestTypeTraits.cxx b/vtkm/testing/UnitTestTypeTraits.cxx index 80280cafb..b830dcebe 100644 --- a/vtkm/testing/UnitTestTypeTraits.cxx +++ b/vtkm/testing/UnitTestTypeTraits.cxx @@ -58,7 +58,7 @@ private: void TestNumeric(T, vtkm::TypeTraitsIntegerTag) const { std::cout << " integer" << std::endl; - typedef typename vtkm::VecTraits::ComponentType VT; + using VT = typename vtkm::VecTraits::ComponentType; VT value = VT(2.001); VTKM_TEST_ASSERT(value == 2, "Integer does not round to integer."); } @@ -66,7 +66,7 @@ private: void TestNumeric(T, vtkm::TypeTraitsRealTag) const { std::cout << " real" << std::endl; - typedef typename vtkm::VecTraits::ComponentType VT; + using VT = typename vtkm::VecTraits::ComponentType; VT value = VT(2.001); VTKM_TEST_ASSERT(test_equal(float(value), float(2.001)), "Real does not hold floaing point number."); diff --git a/vtkm/testing/UnitTestTypes.cxx b/vtkm/testing/UnitTestTypes.cxx index e5dcb0030..acce6cd54 100644 --- a/vtkm/testing/UnitTestTypes.cxx +++ b/vtkm/testing/UnitTestTypes.cxx @@ -45,7 +45,7 @@ void CheckTypeSizes() template void DoGeneralVecTypeTestNegate(const vtkm::Vec&) { - typedef vtkm::Vec VectorType; + using VectorType = vtkm::Vec; for (vtkm::Id valueIndex = 0; valueIndex < 10; valueIndex++) { VectorType original = TestValue(valueIndex, VectorType()); @@ -321,7 +321,7 @@ void GeneralVecTypeTest(const vtkm::Vec&) { std::cout << "Checking general Vec functionality." << std::endl; - typedef vtkm::Vec T; + using T = vtkm::Vec; // Vector types should preserve the trivial properties of their components. // This insures that algorithms like std::copy will optimize fully. @@ -445,7 +445,7 @@ void TypeTest(const vtkm::Vec&) template void TypeTest(const vtkm::Vec&) { - typedef vtkm::Vec Vector; + using Vector = vtkm::Vec; GeneralVecTypeTest(Vector()); @@ -506,7 +506,7 @@ void TypeTest(const vtkm::Vec&) template void TypeTest(const vtkm::Vec&) { - typedef vtkm::Vec Vector; + using Vector = vtkm::Vec; GeneralVecTypeTest(Vector()); @@ -568,7 +568,7 @@ void TypeTest(const vtkm::Vec&) template void TypeTest(const vtkm::Vec&) { - typedef vtkm::Vec Vector; + using Vector = vtkm::Vec; GeneralVecTypeTest(Vector()); diff --git a/vtkm/testing/UnitTestVecAxisAlignedPointCoordinates.cxx b/vtkm/testing/UnitTestVecAxisAlignedPointCoordinates.cxx index 450340899..36e0ce922 100644 --- a/vtkm/testing/UnitTestVecAxisAlignedPointCoordinates.cxx +++ b/vtkm/testing/UnitTestVecAxisAlignedPointCoordinates.cxx @@ -25,7 +25,7 @@ namespace { -typedef vtkm::Vec Vec3; +using Vec3 = vtkm::Vec; static const Vec3 g_Origin = Vec3(1.0f, 2.0f, 3.0f); static const Vec3 g_Spacing = Vec3(4.0f, 5.0f, 6.0f); @@ -79,9 +79,9 @@ template void TryVecAxisAlignedPointCoordinates( const vtkm::VecAxisAlignedPointCoordinates& coords) { - typedef vtkm::VecAxisAlignedPointCoordinates VecCoordsType; - typedef vtkm::TypeTraits TTraits; - typedef vtkm::VecTraits VTraits; + using VecCoordsType = vtkm::VecAxisAlignedPointCoordinates; + using TTraits = vtkm::TypeTraits; + using VTraits = vtkm::VecTraits; std::cout << "Check traits tags." << std::endl; CheckNumericTag(typename TTraits::NumericTag()); diff --git a/vtkm/testing/UnitTestVecFromPortal.cxx b/vtkm/testing/UnitTestVecFromPortal.cxx index 57f6520a6..dbafe3d03 100644 --- a/vtkm/testing/UnitTestVecFromPortal.cxx +++ b/vtkm/testing/UnitTestVecFromPortal.cxx @@ -37,7 +37,7 @@ template class TestPortal { public: - typedef T ValueType; + using ValueType = T; VTKM_EXEC vtkm::Id GetNumberOfValues() const { return ARRAY_SIZE; } @@ -51,10 +51,10 @@ struct VecFromPortalTestFunctor template void operator()(T) const { - typedef TestPortal PortalType; - typedef vtkm::VecFromPortal VecType; - typedef vtkm::TypeTraits TTraits; - typedef vtkm::VecTraits VTraits; + using PortalType = TestPortal; + using VecType = vtkm::VecFromPortal; + using TTraits = vtkm::TypeTraits; + using VTraits = vtkm::VecTraits; std::cout << "Checking VecFromPortal traits" << std::endl; diff --git a/vtkm/testing/UnitTestVecFromPortalPermute.cxx b/vtkm/testing/UnitTestVecFromPortalPermute.cxx index 817cf060c..600565f8d 100644 --- a/vtkm/testing/UnitTestVecFromPortalPermute.cxx +++ b/vtkm/testing/UnitTestVecFromPortalPermute.cxx @@ -39,7 +39,7 @@ template class TestPortal { public: - typedef T ValueType; + using ValueType = T; VTKM_EXEC vtkm::Id GetNumberOfValues() const { return ARRAY_SIZE; } @@ -53,11 +53,11 @@ struct VecFromPortalPermuteTestFunctor template void operator()(T) const { - typedef TestPortal PortalType; - typedef vtkm::VecVariable IndexVecType; - typedef vtkm::VecFromPortalPermute VecType; - typedef vtkm::TypeTraits TTraits; - typedef vtkm::VecTraits VTraits; + using PortalType = TestPortal; + using IndexVecType = vtkm::VecVariable; + using VecType = vtkm::VecFromPortalPermute; + using TTraits = vtkm::TypeTraits; + using VTraits = vtkm::VecTraits; std::cout << "Checking VecFromPortal traits" << std::endl; diff --git a/vtkm/testing/UnitTestVecTraits.cxx b/vtkm/testing/UnitTestVecTraits.cxx index 23064d5cf..78cf883ca 100644 --- a/vtkm/testing/UnitTestVecTraits.cxx +++ b/vtkm/testing/UnitTestVecTraits.cxx @@ -32,8 +32,8 @@ struct TestVecTypeFunctor template void operator()(const T&) const { - typedef vtkm::VecTraits Traits; - typedef typename Traits::ComponentType ComponentType; + using Traits = vtkm::VecTraits; + using ComponentType = typename Traits::ComponentType; VTKM_TEST_ASSERT(Traits::NUM_COMPONENTS <= MAX_VECTOR_SIZE, "Need to update test for larger vectors."); T inVector; diff --git a/vtkm/testing/UnitTestVecVariable.cxx b/vtkm/testing/UnitTestVecVariable.cxx index 9a9df1716..da7171ba8 100644 --- a/vtkm/testing/UnitTestVecVariable.cxx +++ b/vtkm/testing/UnitTestVecVariable.cxx @@ -63,10 +63,10 @@ struct VecVariableTestFunctor void operator()(T) const { static const vtkm::IdComponent SIZE = 5; - typedef vtkm::Vec VecType; - typedef vtkm::VecVariable VecVariableType; - typedef vtkm::TypeTraits TTraits; - typedef vtkm::VecTraits VTraits; + using VecType = vtkm::Vec; + using VecVariableType = vtkm::VecVariable; + using TTraits = vtkm::TypeTraits; + using VTraits = vtkm::VecTraits; std::cout << "Check NumericTag." << std::endl; this->CheckNumericTag(typename TTraits::NumericTag(), diff --git a/vtkm/testing/UnitTestVectorAnalysis.cxx b/vtkm/testing/UnitTestVectorAnalysis.cxx index d6e8ffa81..c216398ea 100644 --- a/vtkm/testing/UnitTestVectorAnalysis.cxx +++ b/vtkm/testing/UnitTestVectorAnalysis.cxx @@ -38,7 +38,7 @@ namespace internal template typename vtkm::VecTraits::ComponentType MyMag(const VectorType& vt) { - typedef vtkm::VecTraits Traits; + using Traits = vtkm::VecTraits; double total = 0.0; for (vtkm::IdComponent index = 0; index < Traits::NUM_COMPONENTS; ++index) { @@ -50,7 +50,7 @@ typename vtkm::VecTraits::ComponentType MyMag(const VectorType& vt) template VectorType MyNormal(const VectorType& vt) { - typedef vtkm::VecTraits Traits; + using Traits = vtkm::VecTraits; typename Traits::ComponentType mag = internal::MyMag(vt); VectorType temp = vt; for (vtkm::IdComponent index = 0; index < Traits::NUM_COMPONENTS; ++index) @@ -70,7 +70,7 @@ T MyLerp(const T& a, const T& b, const W& w) template void TestVector(const VectorType& vector) { - typedef typename vtkm::VecTraits::ComponentType ComponentType; + using ComponentType = typename vtkm::VecTraits::ComponentType; std::cout << "Testing " << vector << std::endl; @@ -127,7 +127,7 @@ void TestCross(const vtkm::Vec& x, const vtkm::Vec& y) { std::cout << "Testing " << x << " x " << y << std::endl; - typedef vtkm::Vec Vec3; + using Vec3 = vtkm::Vec; Vec3 cross = vtkm::Cross(x, y); std::cout << " = " << cross << std::endl; @@ -163,9 +163,9 @@ struct TestLinearFunctor template void operator()(const T&) const { - typedef vtkm::VecTraits Traits; + using Traits = vtkm::VecTraits; const vtkm::IdComponent NUM_COMPONENTS = Traits::NUM_COMPONENTS; - typedef typename Traits::ComponentType ComponentType; + using ComponentType = typename Traits::ComponentType; T zeroVector = T(ComponentType(0)); T normalizedVector = T(vtkm::RSqrt(ComponentType(NUM_COMPONENTS))); diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/collection.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/collection.hpp index c24af95f5..c1b63db70 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/collection.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/collection.hpp @@ -23,23 +23,23 @@ namespace diy typedef detail::Load Load; public: - Collection(Create create, - Destroy destroy, - ExternalStorage* storage, - Save save, - Load load): - create_(create), - destroy_(destroy), - storage_(storage), - save_(save), - load_(load), + Collection(Create create__, + Destroy destroy__, + ExternalStorage* storage__, + Save save__, + Load load__): + create_(create__), + destroy_(destroy__), + storage_(storage__), + save_(save__), + load_(load__), in_memory_(0) {} size_t size() const { return elements_.size(); } const CInt& in_memory() const { return in_memory_; } inline void clear(); - int add(Element e) { elements_.push_back(e); external_.push_back(-1); ++(*in_memory_.access()); return elements_.size() - 1; } + int add(Element e) { elements_.push_back(e); external_.push_back(-1); ++(*in_memory_.access()); return static_cast(elements_.size()) - 1; } void* release(int i) { void* e = get(i); elements_[i] = 0; return e; } void* find(int i) const { return elements_[i]; } // possibly returns 0, if the element is unloaded @@ -81,7 +81,7 @@ clear() { if (own()) for (size_t i = 0; i < size(); ++i) - destroy(i); + destroy(static_cast(i)); elements_.clear(); external_.clear(); *in_memory_.access() = 0; diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/constants.h b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/constants.h index e3c9cc563..3961b628e 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/constants.h +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/constants.h @@ -19,4 +19,6 @@ enum DIY_T1 = 0x80 /* maximum-side t (later) neighbor */ }; +#define DIY_UNUSED(expr) do { (void)(expr); } while (0) + #endif diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/decomposition.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/decomposition.hpp index 51dfc5af2..608573d1b 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/decomposition.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/decomposition.hpp @@ -281,7 +281,7 @@ void diy::RegularDecomposer:: decompose(int rank, const Assigner& assigner, Master& master) { - decompose(rank, assigner, [&master](int gid, const Bounds& core, const Bounds& bounds, const Bounds& domain, const Link& link) + decompose(rank, assigner, [&master](int gid, const Bounds& core, const Bounds& bounds, const Bounds&, const Link& link) { void* b = master.create(); Link* l = new Link(link); @@ -314,49 +314,49 @@ decompose(int rank, const Assigner& assigner, const Creator& create) while (!all(offsets, 1)) { // next offset - int i; - for (i = 0; i < dim; ++i) - if (offsets[i] == 1) - offsets[i] = -1; + int j; + for (j = 0; j < dim; ++j) + if (offsets[j] == 1) + offsets[j] = -1; else break; - ++offsets[i]; + ++offsets[j]; if (all(offsets, 0)) continue; // skip ourselves DivisionsVector nhbr_coords(dim); Direction dir, wrap_dir; bool inbounds = true; - for (int i = 0; i < dim; ++i) + for (int k = 0; k < dim; ++k) { - nhbr_coords[i] = coords[i] + offsets[i]; + nhbr_coords[k] = coords[k] + offsets[k]; // wrap - if (nhbr_coords[i] < 0) + if (nhbr_coords[k] < 0) { - if (wrap[i]) + if (wrap[k]) { - nhbr_coords[i] = divisions[i] - 1; - wrap_dir[i] = -1; + nhbr_coords[k] = divisions[k] - 1; + wrap_dir[k] = -1; } else inbounds = false; } - if (nhbr_coords[i] >= divisions[i]) + if (nhbr_coords[k] >= divisions[k]) { - if (wrap[i]) + if (wrap[k]) { - nhbr_coords[i] = 0; - wrap_dir[i] = 1; + nhbr_coords[k] = 0; + wrap_dir[k] = 1; } else inbounds = false; } // NB: this needs to match the addressing scheme in dir_t (in constants.h) - if (offsets[i] == -1 || offsets[i] == 1) - dir[i] = offsets[i]; + if (offsets[k] == -1 || offsets[k] == 1) + dir[k] = offsets[k]; } if (!inbounds) continue; @@ -382,12 +382,12 @@ void diy::RegularDecomposer:: decompose(int rank, const Assigner& assigner, Master& master, const Updater& update) { - decompose(rank, assigner, [&master,&update](int gid, const Bounds& core, const Bounds& bounds, const Bounds& domain, const Link& link) + decompose(rank, assigner, [&master,&update](int gid, const Bounds& core, const Bounds& bounds, const Bounds& domain_, const Link& link) { int lid = master.lid(gid); Link* l = new Link(link); master.replace_link(lid, l); - update(gid, lid, core, bounds, domain, *l); + update(gid, lid, core, bounds, domain_, *l); }); } @@ -407,7 +407,7 @@ void diy::RegularDecomposer:: gid_to_coords(int gid, DivisionsVector& coords, const DivisionsVector& divisions) { - int dim = divisions.size(); + int dim = static_cast(divisions.size()); for (int i = 0; i < dim; ++i) { coords.push_back(gid % divisions[i]); @@ -421,7 +421,7 @@ diy::RegularDecomposer:: coords_to_gid(const DivisionsVector& coords, const DivisionsVector& divisions) { int gid = 0; - for (int i = coords.size() - 1; i >= 0; --i) + for (int i = static_cast(coords.size()) - 1; i >= 0; --i) { gid *= divisions[i]; gid += coords[i]; @@ -515,21 +515,21 @@ struct Div template void diy::RegularDecomposer:: -fill_divisions(std::vector& divisions) const +fill_divisions(std::vector& divisions_) const { // prod = number of blocks unconstrained by user; c = number of unconstrained dimensions int prod = 1; int c = 0; for (int i = 0; i < dim; ++i) - if (divisions[i] != 0) + if (divisions_[i] != 0) { - prod *= divisions[i]; + prod *= divisions_[i]; ++c; } if (nblocks % prod != 0) throw std::runtime_error("Total number of blocks cannot be factored into provided divs"); - if (c == (int) divisions.size()) // nothing to do; user provided all divs + if (c == (int) divisions_.size()) // nothing to do; user provided all divs return; // factor number of blocks left in unconstrained dimensions @@ -543,7 +543,7 @@ fill_divisions(std::vector& divisions) const // init missing_divs for (int i = 0; i < dim; i++) { - if (divisions[i] == 0) + if (divisions_[i] == 0) { Div div; div.dim = i; @@ -592,7 +592,7 @@ fill_divisions(std::vector& divisions) const // assign the divisions for (size_t i = 0; i < missing_divs.size(); i++) - divisions[missing_divs[i].dim] = missing_divs[i].nb; + divisions_[missing_divs[i].dim] = missing_divs[i].nb; } template diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree-sampling.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree-sampling.hpp index 7cf2ee1e5..f7b4c977c 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree-sampling.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree-sampling.hpp @@ -299,8 +299,8 @@ add_samples(Block* b, const diy::ReduceProxy& srp, Samples& samples) const Samples smpls; srp.dequeue(nbr_gid, smpls); - for (size_t i = 0; i < smpls.size(); ++i) - samples.push_back(smpls[i]); + for (size_t j = 0; j < smpls.size(); ++j) + samples.push_back(smpls[j]); } } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree.hpp index 286929dc9..38167eb22 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/kdtree.hpp @@ -399,8 +399,8 @@ add_histogram(Block* b, const diy::ReduceProxy& srp, Histogram& histogram) const Histogram hist; srp.dequeue(nbr_gid, hist); - for (size_t i = 0; i < hist.size(); ++i) - histogram[i] += hist[i]; + for (size_t j = 0; j < hist.size(); ++j) + histogram[j] += hist[j]; } } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/sort.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/sort.hpp index 5cc3f8807..3e9ffd82f 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/sort.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/algorithms/sort.hpp @@ -51,10 +51,10 @@ struct SampleSort { if (skip_self && rp.in_link().target(i).gid == rp.gid()) continue; MemoryBuffer& in = rp.incoming(rp.in_link().target(i).gid); - size_t sz = in.size() / sizeof(T); + size_t incoming_sz = in.size() / sizeof(T); T* bg = (T*) &in.buffer[0]; - std::copy(bg, bg + sz, &v[end]); - end += sz; + std::copy(bg, bg + incoming_sz, &v[end]); + end += incoming_sz; } } else { diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/reduce/all-to-all.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/reduce/all-to-all.hpp index 1e555db82..7e3082547 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/reduce/all-to-all.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/detail/reduce/all-to-all.hpp @@ -132,7 +132,6 @@ namespace detail { MemoryBuffer& in = srp.incoming(srp.in_link().target(i).gid); - std::pair range; load(in, range); std::pair from_to; diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/block.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/block.hpp index 05e45a800..1a2527ccc 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/block.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/block.hpp @@ -5,15 +5,12 @@ #include #include -#include -#include -#include - #include "../mpi.hpp" #include "../assigner.hpp" #include "../master.hpp" #include "../storage.hpp" #include "../log.hpp" +#include "utils.hpp" // Read and write collections of blocks using MPI-IO namespace diy @@ -41,7 +38,7 @@ namespace io } } -// Serialize GidOffsetCount explicitly, to avoid alignment and unitialized data issues +// Serialize GidOffsetCount explicitly, to avoid alignment and uninitialized data issues // (to get identical output files given the same block input) template<> struct Serialization @@ -89,14 +86,13 @@ namespace io // truncate the file if (comm.rank() == 0) - truncate(outfilename.c_str(), 0); + diy::io::utils::truncate(outfilename.c_str(), 0); mpi::io::file f(comm, outfilename, mpi::io::file::wronly | mpi::io::file::create); offset_t start = 0, shift; std::vector offset_counts; - unsigned i; - for (i = 0; i < max_size; ++i) + for (unsigned i = 0; i < max_size; ++i) { offset_t count = 0, offset; @@ -140,12 +136,12 @@ namespace io std::vector all_offset_counts; for (unsigned i = 0; i < gathered_offset_count_buffers.size(); ++i) { - MemoryBuffer oc_buffer; oc_buffer.buffer.swap(gathered_offset_count_buffers[i]); - std::vector offset_counts; - diy::load(oc_buffer, offset_counts); - for (unsigned j = 0; j < offset_counts.size(); ++j) - if (offset_counts[j].gid != -1) - all_offset_counts.push_back(offset_counts[j]); + MemoryBuffer per_rank_oc_buffer; per_rank_oc_buffer.buffer.swap(gathered_offset_count_buffers[i]); + std::vector per_rank_offset_counts; + diy::load(per_rank_oc_buffer, per_rank_offset_counts); + for (unsigned j = 0; j < per_rank_offset_counts.size(); ++j) + if (per_rank_offset_counts[j].gid != -1) + all_offset_counts.push_back(per_rank_offset_counts[j]); } std::sort(all_offset_counts.begin(), all_offset_counts.end()); // sorts by gid @@ -278,13 +274,11 @@ namespace split size_t size = 0; if (comm.rank() == 0) { - struct stat s; - if (stat(outfilename.c_str(), &s) == 0) - { - if (S_ISDIR(s.st_mode)) - proceed = true; - } else if (mkdir(outfilename.c_str(), 0755) == 0) - proceed = true; + if (diy::io::utils::is_directory(outfilename)) + proceed = true; + else if (diy::io::utils::make_directory(outfilename)) + proceed = true; + mpi::broadcast(comm, proceed, 0); mpi::reduce(comm, (size_t) master.size(), size, 0, std::plus()); } else @@ -338,12 +332,14 @@ namespace split // load the extra buffer and size size_t size; - std::string filename = infilename + "/extra"; - ::diy::detail::FileBuffer bb(fopen(filename.c_str(), "r")); - ::diy::load(bb, size); - ::diy::load(bb, extra); - extra.reset(); - fclose(bb.file); + { + std::string filename = infilename + "/extra"; + ::diy::detail::FileBuffer bb(fopen(filename.c_str(), "r")); + ::diy::load(bb, size); + ::diy::load(bb, extra); + extra.reset(); + fclose(bb.file); + } // Get local gids from assigner assigner.set_nblocks(size); diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/bov.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/bov.hpp index bd8b24009..18bf90426 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/bov.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/bov.hpp @@ -71,6 +71,7 @@ void diy::io::BOV:: read(const DiscreteBounds& bounds, T* buffer, bool collective, int chunk) const { +#ifndef DIY_NO_MPI int dim = shape_.size(); int total = 1; std::vector subsizes; @@ -110,6 +111,10 @@ read(const DiscreteBounds& bounds, T* buffer, bool collective, int chunk) const if (chunk != 1) MPI_Type_free(&T_type); MPI_Type_free(&fileblk); +#else + (void) bounds; (void) buffer; (void) collective; (void)chunk; + DIY_UNSUPPORTED_MPI_CALL(diy::io::BOV::read); +#endif } template @@ -125,6 +130,7 @@ void diy::io::BOV:: write(const DiscreteBounds& bounds, const T* buffer, const DiscreteBounds& core, bool collective, int chunk) { +#ifndef DIY_NO_MPI int dim = shape_.size(); std::vector subsizes; std::vector buffer_shape, buffer_start; @@ -166,6 +172,10 @@ write(const DiscreteBounds& bounds, const T* buffer, const DiscreteBounds& core, MPI_Type_free(&T_type); MPI_Type_free(&fileblk); MPI_Type_free(&subbuffer); +#else + (void) bounds; (void) buffer;(void) core; (void) collective; (void) chunk; + DIY_UNSUPPORTED_MPI_CALL(diy::io::bov::write); +#endif } #endif diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/utils.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/utils.hpp new file mode 100644 index 000000000..93113346d --- /dev/null +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/io/utils.hpp @@ -0,0 +1,113 @@ +#ifndef DIY_IO_UTILS_HPP +#define DIY_IO_UTILS_HPP + +#if defined(_WIN32) +#include +#include +#else +#include // mkstemp() on Mac +#include +#endif + +#include // remove() +#include // mkstemp() on Linux +#include + +namespace diy +{ +namespace io +{ +namespace utils +{ + /** + * returns true if the filename exists and refers to a directory. + */ + inline bool is_directory(const std::string& filename) + { +#if defined(_WIN32) + DWORD attr = GetFileAttributes(filename.c_str()); + return (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0); +#else + struct stat s; + return (stat(filename.c_str(), &s) == 0 && S_ISDIR(s.st_mode)); +#endif + } + + /** + * creates a new directory. returns true on success. + */ + inline bool make_directory(const std::string& filename) + { +#if defined(_WIN32) + return _mkdir(filename.c_str()) == 0; +#else + return mkdir(filename.c_str(), 0755) == 0; +#endif + } + + /** + * truncates a file to the given length, if the file exists and can be opened + * for writing. + */ + inline void truncate(const std::string& filename, size_t length) + { +#if defined(_WIN32) + int fd = -1; + _sopen_s(&fd, filename.c_str(), _O_WRONLY | _O_BINARY, _SH_DENYNO, _S_IWRITE); + if (fd != -1) + { + _chsize_s(fd, 0); + _close(fd); + } +#else + ::truncate(filename.c_str(), length); +#endif + } + + inline int mkstemp(std::string& filename) + { + const size_t slen = filename.size(); + char *s_template = new char[filename.size() + 1]; + std::copy_n(filename.c_str(), slen+1, s_template); + + int handle = -1; +#if defined(_WIN32) + if (_mktemp_s(s_template, slen+1) == 0) // <- returns 0 on success. + _sopen_s(&handle, s_template, _O_WRONLY | _O_CREAT | _O_BINARY, _SH_DENYNO, _S_IWRITE); +#elif defined(__MACH__) + // TODO: figure out how to open with O_SYNC + handle = ::mkstemp(s_template); +#else + handle = mkostemp(s_template, O_WRONLY | O_SYNC); +#endif + if (handle != -1) + filename = s_template; + return handle; + } + + inline void close(int fd) + { +#if defined(_WIN32) + _close(fd); +#else + fsync(fd); + close(fd); +#endif + } + + inline void sync(int fd) + { +#if !defined(_WIN32) + fsync(fd); +#endif + } + + inline bool remove(const std::string& filename) + { + return ::remove(filename.c_str()) == 0; + } +} +} +} + +#endif diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/link.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/link.hpp index 3262eef61..7f5e8b4a4 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/link.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/link.hpp @@ -17,7 +17,7 @@ namespace diy public: virtual ~Link() {} // need to be able to delete derived classes - int size() const { return neighbors_.size(); } + int size() const { return static_cast(neighbors_.size()); } inline int size_unique() const; BlockID target(int i) const { return neighbors_[i]; } @@ -201,7 +201,7 @@ size_unique() const { std::vector tmp(neighbors_.begin(), neighbors_.end()); std::sort(tmp.begin(), tmp.end()); - return std::unique(tmp.begin(), tmp.end()) - tmp.begin(); + return static_cast(std::unique(tmp.begin(), tmp.end()) - tmp.begin()); } template diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/log.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/log.hpp index 45f202f92..168187d92 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/log.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/log.hpp @@ -15,12 +15,12 @@ namespace spd struct logger { // logger.info(cppformat_string, arg1, arg2, arg3, ...) call style - template void trace(const char* fmt, const Args&... args) {} - template void debug(const char* fmt, const Args&... args) {} - template void info(const char* fmt, const Args&... args) {} - template void warn(const char* fmt, const Args&... args) {} - template void error(const char* fmt, const Args&... args) {} - template void critical(const char* fmt, const Args&... args) {} + template void trace(const char*, const Args&...) {} + template void debug(const char*, const Args&...) {} + template void info(const char*, const Args&...) {} + template void warn(const char*, const Args&...) {} + template void error(const char*, const Args&...) {} + template void critical(const char*, const Args&...) {} }; } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/master.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/master.hpp index 97ccb8724..84e556a81 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/master.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/master.hpp @@ -52,7 +52,7 @@ namespace diy using Skip = std::function; struct SkipNoIncoming; - struct NeverSkip { bool operator()(int i, const Master& master) const { return false; } }; + struct NeverSkip { bool operator()(int, const Master&) const { return false; } }; // Collection typedef Collection::Create CreateBlock; @@ -80,8 +80,8 @@ namespace diy struct QueueSizePolicy: public QueuePolicy { QueueSizePolicy(size_t sz): size(sz) {} - bool unload_incoming(const Master& master, int from, int to, size_t sz) const { return sz > size; } - bool unload_outgoing(const Master& master, int from, size_t sz) const { return sz > size*master.outgoing_count(from); } + bool unload_incoming(const Master&, int, int, size_t sz) const { return sz > size; } + bool unload_outgoing(const Master& master, int from, size_t sz) const { return sz > size*master.outgoing_count(from); } size_t size; }; @@ -162,15 +162,15 @@ namespace diy * serialize a block */ Master(mpi::communicator comm, //!< communicator - int threads = 1, //!< number of threads DIY can use - int limit = -1, //!< number of blocks to store in memory - CreateBlock create = 0, //!< block create function; master manages creation if create != 0 - DestroyBlock destroy = 0, //!< block destroy function; master manages destruction if destroy != 0 - ExternalStorage* storage = 0, //!< storage object (path, method, etc.) for storing temporary blocks being shuffled in/out of core - SaveBlock save = 0, //!< block save function; master manages saving if save != 0 - LoadBlock load = 0, //!< block load function; master manages loading if load != 0 - QueuePolicy* q_policy = new QueueSizePolicy(4096)): //!< policy for managing message queues specifies maximum size of message queues to keep in memory - blocks_(create, destroy, storage, save, load), + int threads = 1, //!< number of threads DIY can use + int limit = -1, //!< number of blocks to store in memory + CreateBlock create_ = 0, //!< block create function; master manages creation if create != 0 + DestroyBlock destroy_ = 0, //!< block destroy function; master manages destruction if destroy != 0 + ExternalStorage* storage = 0, //!< storage object (path, method, etc.) for storing temporary blocks being shuffled in/out of core + SaveBlock save = 0, //!< block save function; master manages saving if save != 0 + LoadBlock load_ = 0, //!< block load function; master manages loading if load != 0 + QueuePolicy* q_policy = new QueueSizePolicy(4096)): //!< policy for managing message queues specifies maximum size of message queues to keep in memory + blocks_(create_, destroy_, storage, save, load_), queue_policy_(q_policy), limit_(limit), threads_(threads == -1 ? thread::hardware_concurrency() : threads), @@ -230,7 +230,7 @@ namespace diy ProxyWithLink proxy(int i) const; //! return the number of local blocks - unsigned size() const { return blocks_.size(); } + unsigned int size() const { return static_cast(blocks_.size()); } void* create() const { return blocks_.create(); } // accessors @@ -666,7 +666,7 @@ add(int gid, void* b, Link* l) links_.push_back(l); gids_.push_back(gid); - int lid = gids_.size() - 1; + int lid = static_cast(gids_.size()) - 1; lids_[gid] = lid; add_expected(l->size_unique()); // NB: at every iteration we expect a message from each unique neighbor @@ -703,6 +703,8 @@ diy::Master:: foreach_(const Callback& f, const Skip& skip) { auto scoped = prof.scoped("foreach"); + DIY_UNUSED(scoped); + commands_.push_back(new Command(f, skip)); if (immediate()) @@ -715,6 +717,7 @@ execute() { log->debug("Entered execute()"); auto scoped = prof.scoped("execute"); + DIY_UNUSED(scoped); //show_incoming_records(); // touch the outgoing and incoming queues as well as collectives to make sure they exist @@ -798,6 +801,8 @@ diy::Master:: exchange() { auto scoped = prof.scoped("exchange"); + DIY_UNUSED(scoped); + execute(); log->debug("Starting exchange"); @@ -1087,9 +1092,9 @@ flush() // XXX: with queues we could easily maintain a specific space limit int out_queues_limit; if (limit_ == -1 || size() == 0) - out_queues_limit = to_send.size(); + out_queues_limit = static_cast(to_send.size()); else - out_queues_limit = std::max((size_t) 1, to_send.size()/size()*limit_); // average number of queues per block * in-memory block limit + out_queues_limit = static_cast(std::max((size_t) 1, to_send.size()/size()*limit_)); // average number of queues per block * in-memory block limit do { @@ -1119,6 +1124,7 @@ diy::Master:: process_collectives() { auto scoped = prof.scoped("collectives"); + DIY_UNUSED(scoped); if (collectives_.empty()) return; @@ -1157,15 +1163,17 @@ diy::Master:: nudge() { bool success = false; - for (InFlightSendsList::iterator it = inflight_sends_.begin(); it != inflight_sends_.end(); ++it) + for (InFlightSendsList::iterator it = inflight_sends_.begin(); it != inflight_sends_.end();) { mpi::optional ostatus = it->request.test(); if (ostatus) { success = true; - InFlightSendsList::iterator rm = it; - --it; - inflight_sends_.erase(rm); + it = inflight_sends_.erase(it); + } + else + { + ++it; } } return success; diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi.hpp index 28502002f..ed0075ccd 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi.hpp @@ -1,7 +1,11 @@ #ifndef DIY_MPI_HPP #define DIY_MPI_HPP +#ifndef DIY_NO_MPI #include +#else +#include "mpi/no-mpi.hpp" +#endif #include "mpi/constants.hpp" #include "mpi/datatypes.hpp" @@ -21,12 +25,39 @@ namespace mpi //! \ingroup MPI struct environment { - environment() { int argc = 0; char** argv; MPI_Init(&argc, &argv); } - environment(int argc, char* argv[]) { MPI_Init(&argc, &argv); } - ~environment() { MPI_Finalize(); } + inline environment(); + inline environment(int argc, char* argv[]); + inline ~environment(); }; } } +diy::mpi::environment:: +environment() +{ +#ifndef DIY_NO_MPI + int argc = 0; char** argv; + MPI_Init(&argc, &argv); +#endif +} + +diy::mpi::environment:: +environment(int argc, char* argv[]) +{ +#ifndef DIY_NO_MPI + MPI_Init(&argc, &argv); +#else + (void) argc; (void) argv; +#endif +} + +diy::mpi::environment:: +~environment() +{ +#ifndef DIY_NO_MPI + MPI_Finalize(); +#endif +} + #endif diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/collectives.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/collectives.hpp index 8d70bcf01..1d7936da2 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/collectives.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/collectives.hpp @@ -16,13 +16,16 @@ namespace mpi static void broadcast(const communicator& comm, T& x, int root) { +#ifndef DIY_NO_MPI MPI_Bcast(Datatype::address(x), Datatype::count(x), Datatype::datatype(), root, comm); +#endif } static void broadcast(const communicator& comm, std::vector& x, int root) { +#ifndef DIY_NO_MPI size_t sz = x.size(); Collectives::broadcast(comm, sz, root); @@ -32,15 +35,21 @@ namespace mpi MPI_Bcast(Datatype::address(x[0]), x.size(), Datatype::datatype(), root, comm); +#endif } static request ibroadcast(const communicator& comm, T& x, int root) { +#ifndef DIY_NO_MPI request r; MPI_Ibcast(Datatype::address(x), Datatype::count(x), Datatype::datatype(), root, comm, &r.r); return r; +#else + (void)x; (void)root; + DIY_UNSUPPORTED_MPI_CALL(MPI_Ibcast); +#endif } static void gather(const communicator& comm, const T& in, std::vector& out, int root) @@ -48,6 +57,7 @@ namespace mpi size_t s = comm.size(); s *= Datatype::count(in); out.resize(s); +#ifndef DIY_NO_MPI MPI_Gather(Datatype::address(const_cast(in)), Datatype::count(in), Datatype::datatype(), @@ -55,10 +65,15 @@ namespace mpi Datatype::count(in), Datatype::datatype(), root, comm); +#else + (void) root; + out[0] = in; +#endif } static void gather(const communicator& comm, const std::vector& in, std::vector< std::vector >& out, int root) { +#ifndef DIY_NO_MPI std::vector counts(comm.size()); Collectives::gather(comm, (int) in.size(), counts, root); @@ -84,10 +99,16 @@ namespace mpi for (unsigned j = 0; j < (unsigned)counts[i]; ++j) out[i].push_back(buffer[cur++]); } +#else + (void) comm; (void) root; + out.resize(1); + out[0] = in; +#endif } static void gather(const communicator& comm, const T& in, int root) { +#ifndef DIY_NO_MPI MPI_Gather(Datatype::address(const_cast(in)), Datatype::count(in), Datatype::datatype(), @@ -95,10 +116,14 @@ namespace mpi Datatype::count(in), Datatype::datatype(), root, comm); +#else + DIY_UNSUPPORTED_MPI_CALL("MPI_Gather"); +#endif } static void gather(const communicator& comm, const std::vector& in, int root) { +#ifndef DIY_NO_MPI Collectives::gather(comm, (int) in.size(), root); MPI_Gatherv(Datatype::address(const_cast(in[0])), @@ -107,6 +132,9 @@ namespace mpi 0, 0, 0, Datatype::datatype(), root, comm); +#else + DIY_UNSUPPORTED_MPI_CALL("MPI_Gatherv"); +#endif } static void all_gather(const communicator& comm, const T& in, std::vector& out) @@ -114,6 +142,7 @@ namespace mpi size_t s = comm.size(); s *= Datatype::count(in); out.resize(s); +#ifndef DIY_NO_MPI MPI_Allgather(Datatype::address(const_cast(in)), Datatype::count(in), Datatype::datatype(), @@ -121,10 +150,14 @@ namespace mpi Datatype::count(in), Datatype::datatype(), comm); +#else + out[0] = in; +#endif } static void all_gather(const communicator& comm, const std::vector& in, std::vector< std::vector >& out) { +#ifndef DIY_NO_MPI std::vector counts(comm.size()); Collectives::all_gather(comm, (int) in.size(), counts); @@ -150,40 +183,60 @@ namespace mpi for (int j = 0; j < counts[i]; ++j) out[i].push_back(buffer[cur++]); } +#else + (void) comm; + out.resize(1); + out[0] = in; +#endif } static void reduce(const communicator& comm, const T& in, T& out, int root, const Op&) { +#ifndef DIY_NO_MPI MPI_Reduce(Datatype::address(const_cast(in)), Datatype::address(out), Datatype::count(in), Datatype::datatype(), detail::mpi_op::get(), root, comm); +#else + (void) comm; (void) root; + out = in; +#endif } static void reduce(const communicator& comm, const T& in, int root, const Op& op) { +#ifndef DIY_NO_MPI MPI_Reduce(Datatype::address(const_cast(in)), Datatype::address(const_cast(in)), Datatype::count(in), Datatype::datatype(), detail::mpi_op::get(), root, comm); +#else + DIY_UNSUPPORTED_MPI_CALL("MPI_Reduce"); +#endif } static void all_reduce(const communicator& comm, const T& in, T& out, const Op&) { +#ifndef DIY_NO_MPI MPI_Allreduce(Datatype::address(const_cast(in)), Datatype::address(out), Datatype::count(in), Datatype::datatype(), detail::mpi_op::get(), comm); +#else + (void) comm; + out = in; +#endif } static void all_reduce(const communicator& comm, const std::vector& in, std::vector& out, const Op&) { +#ifndef DIY_NO_MPI out.resize(in.size()); MPI_Allreduce(Datatype::address(const_cast(in[0])), Datatype::address(out[0]), @@ -191,26 +244,39 @@ namespace mpi Datatype::datatype(), detail::mpi_op::get(), comm); +#else + out = in; +#endif } static void scan(const communicator& comm, const T& in, T& out, const Op&) { +#ifndef DIY_NO_MPI MPI_Scan(Datatype::address(const_cast(in)), Datatype::address(out), Datatype::count(in), Datatype::datatype(), detail::mpi_op::get(), comm); +#else + (void) comm; + out = in; +#endif } static void all_to_all(const communicator& comm, const std::vector& in, std::vector& out, int n = 1) { +#ifndef DIY_NO_MPI // NB: this will fail if T is a vector MPI_Alltoall(Datatype::address(const_cast(in[0])), n, Datatype::datatype(), Datatype::address(out[0]), n, Datatype::datatype(), comm); +#else + (void) comm; (void) n; + out = in; +#endif } }; diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/communicator.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/communicator.hpp index c29b6d033..fa4bc0b54 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/communicator.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/communicator.hpp @@ -8,8 +8,8 @@ namespace mpi class communicator { public: - communicator(MPI_Comm comm = MPI_COMM_WORLD): - comm_(comm), rank_(0), size_(1) { if (comm != MPI_COMM_NULL) { MPI_Comm_rank(comm_, &rank_); MPI_Comm_size(comm_, &size_); } } + inline + communicator(MPI_Comm comm = MPI_COMM_WORLD); int rank() const { return rank_; } int size() const { return size_; } @@ -33,12 +33,13 @@ namespace mpi request isend(int dest, int tag, const T& x) const { return detail::isend()(comm_, dest, tag, x); } //! Non-blocking version of `recv()`. - //! If `T` is an `std::vector<...>`, its size must be big enough to accomodate the sent values. + //! If `T` is an `std::vector<...>`, its size must be big enough to accommodate the sent values. template request irecv(int source, int tag, T& x) const { return detail::irecv()(comm_, source, tag, x); } //! probe - status probe(int source, int tag) const { status s; MPI_Probe(source, tag, comm_, &s.s); return s; } + inline + status probe(int source, int tag) const; //! iprobe inline @@ -46,7 +47,8 @@ namespace mpi iprobe(int source, int tag) const; //! barrier - void barrier() const { MPI_Barrier(comm_); } + inline + void barrier() const; operator MPI_Comm() const { return comm_; } @@ -58,15 +60,56 @@ namespace mpi } } +diy::mpi::communicator:: +communicator(MPI_Comm comm) +:comm_(comm), rank_(0), size_(1) +{ +#ifndef DIY_NO_MPI + if (comm != MPI_COMM_NULL) + { + MPI_Comm_rank(comm_, &rank_); + MPI_Comm_size(comm_, &size_); + } +#endif +} + +diy::mpi::status +diy::mpi::communicator:: +probe(int source, int tag) const +{ + (void) source; + (void) tag; + +#ifndef DIY_NO_MPI + status s; + MPI_Probe(source, tag, comm_, &s.s); + return s; +#else + DIY_UNSUPPORTED_MPI_CALL(MPI_Probe); +#endif +} + diy::mpi::optional diy::mpi::communicator:: iprobe(int source, int tag) const { + (void) source; + (void) tag; +#ifndef DIY_NO_MPI status s; int flag; MPI_Iprobe(source, tag, comm_, &flag, &s.s); if (flag) return s; +#endif return optional(); } +void +diy::mpi::communicator:: +barrier() const +{ +#ifndef DIY_NO_MPI + MPI_Barrier(comm_); +#endif +} diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/datatypes.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/datatypes.hpp index 7d8e3a448..0d950a14c 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/datatypes.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/datatypes.hpp @@ -42,7 +42,7 @@ namespace detail static MPI_Datatype datatype() { return get_mpi_datatype(); } static const void* address(const T& x) { return &x; } static void* address(T& x) { return &x; } - static int count(const T& x) { return 1; } + static int count(const T&) { return 1; } }; template @@ -53,7 +53,7 @@ namespace detail static MPI_Datatype datatype() { return get_mpi_datatype(); } static const void* address(const VecU& x) { return &x[0]; } static void* address(VecU& x) { return &x[0]; } - static int count(const VecU& x) { return x.size(); } + static int count(const VecU& x) { return static_cast(x.size()); } }; } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/io.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/io.hpp index ebe6a2e17..05c6f6b3b 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/io.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/io.hpp @@ -1,6 +1,8 @@ #ifndef DIY_MPI_IO_HPP #define DIY_MPI_IO_HPP +#include "../constants.h" + #include #include @@ -30,15 +32,12 @@ namespace io }; public: - file(const communicator& comm, - const std::string& filename, - int mode): - comm_(comm) { MPI_File_open(comm, const_cast(filename.c_str()), mode, MPI_INFO_NULL, &fh); } + inline file(const communicator& comm, const std::string& filename, int mode); ~file() { close(); } - void close() { if (fh != MPI_FILE_NULL) MPI_File_close(&fh); } + inline void close(); - offset size() const { offset sz; MPI_File_get_size(fh, &sz); return sz; } - void resize(offset size) { MPI_File_set_size(fh, size); } + inline offset size() const; + inline void resize(offset size); inline void read_at(offset o, char* buffer, size_t size); inline void read_at_all(offset o, char* buffer, size_t size); @@ -70,12 +69,67 @@ namespace io } } +diy::mpi::io::file:: +file(const communicator& comm, const std::string& filename, int mode) +: comm_(comm) +{ +#ifndef DIY_NO_MPI + MPI_File_open(comm, const_cast(filename.c_str()), mode, MPI_INFO_NULL, &fh); +#else + DIY_UNUSED(filename); + DIY_UNUSED(mode); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_open); +#endif +} + +void +diy::mpi::io::file:: +close() +{ +#ifndef DIY_NO_MPI + if (fh != MPI_FILE_NULL) + MPI_File_close(&fh); +#endif +} + +diy::mpi::io::offset +diy::mpi::io::file:: +size() const +{ +#ifndef DIY_NO_MPI + offset sz; + MPI_File_get_size(fh, &sz); + return sz; +#else + DIY_UNSUPPORTED_MPI_CALL(MPI_File_get_size); +#endif +} + +void +diy::mpi::io::file:: +resize(diy::mpi::io::offset size) +{ +#ifndef DIY_NO_MPI + MPI_File_set_size(fh, size); +#else + DIY_UNUSED(size); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_set_size); +#endif +} + void diy::mpi::io::file:: read_at(offset o, char* buffer, size_t size) { +#ifndef DIY_NO_MPI status s; - MPI_File_read_at(fh, o, buffer, size, detail::get_mpi_datatype(), &s.s); + MPI_File_read_at(fh, o, buffer, static_cast(size), detail::get_mpi_datatype(), &s.s); +#else + DIY_UNUSED(o); + DIY_UNUSED(buffer); + DIY_UNUSED(size); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_read_at); +#endif } template @@ -90,8 +144,15 @@ void diy::mpi::io::file:: read_at_all(offset o, char* buffer, size_t size) { +#ifndef DIY_NO_MPI status s; - MPI_File_read_at_all(fh, o, buffer, size, detail::get_mpi_datatype(), &s.s); + MPI_File_read_at_all(fh, o, buffer, static_cast(size), detail::get_mpi_datatype(), &s.s); +#else + DIY_UNUSED(o); + DIY_UNUSED(buffer); + DIY_UNUSED(size); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_read_at_all); +#endif } template @@ -106,8 +167,15 @@ void diy::mpi::io::file:: write_at(offset o, const char* buffer, size_t size) { +#ifndef DIY_NO_MPI status s; - MPI_File_write_at(fh, o, (void *)buffer, size, detail::get_mpi_datatype(), &s.s); + MPI_File_write_at(fh, o, (void *)buffer, static_cast(size), detail::get_mpi_datatype(), &s.s); +#else + DIY_UNUSED(o); + DIY_UNUSED(buffer); + DIY_UNUSED(size); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_write_at); +#endif } template @@ -122,8 +190,15 @@ void diy::mpi::io::file:: write_at_all(offset o, const char* buffer, size_t size) { +#ifndef DIY_NO_MPI status s; - MPI_File_write_at_all(fh, o, (void *)buffer, size, detail::get_mpi_datatype(), &s.s); + MPI_File_write_at_all(fh, o, (void *)buffer, static_cast(size), detail::get_mpi_datatype(), &s.s); +#else + DIY_UNUSED(o); + DIY_UNUSED(buffer); + DIY_UNUSED(size); + DIY_UNSUPPORTED_MPI_CALL(MPI_File_write_at_all); +#endif } template diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/no-mpi.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/no-mpi.hpp new file mode 100644 index 000000000..bf96ea33c --- /dev/null +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/no-mpi.hpp @@ -0,0 +1,70 @@ +#ifndef DIY_MPI_NO_MPI_HPP +#define DIY_MPI_NO_MPI_HPP + +#include // std::runtime_error + + +static const int MPI_SUCCESS = 0; +static const int MPI_ANY_SOURCE = -1; +static const int MPI_ANY_TAG = -1; + +/* define communicator type and constants */ +using MPI_Comm = int; +static const MPI_Comm MPI_COMM_NULL = 0; +static const MPI_Comm MPI_COMM_WORLD = 1; + +/* define datatypes */ +using MPI_Datatype = size_t; + +#define DIY_NO_MPI_DATATYPE(cpp_type, mpi_type) \ + static const MPI_Datatype mpi_type = sizeof(cpp_type); +DIY_NO_MPI_DATATYPE(char, MPI_BYTE); +DIY_NO_MPI_DATATYPE(int, MPI_INT); +DIY_NO_MPI_DATATYPE(unsigned, MPI_UNSIGNED); +DIY_NO_MPI_DATATYPE(long, MPI_LONG); +DIY_NO_MPI_DATATYPE(unsigned long, MPI_UNSIGNED_LONG); +DIY_NO_MPI_DATATYPE(long long, MPI_LONG_LONG_INT); +DIY_NO_MPI_DATATYPE(unsigned long long, MPI_UNSIGNED_LONG_LONG); +DIY_NO_MPI_DATATYPE(float, MPI_FLOAT); +DIY_NO_MPI_DATATYPE(double, MPI_DOUBLE); +#endif + +/* status type */ +struct MPI_Status +{ + /* These fields are publicly defined in the MPI specification. + User applications may freely read from these fields. */ + int MPI_SOURCE; + int MPI_TAG; + int MPI_ERROR; +}; + +/* define MPI_Request */ +using MPI_Request = int; + +#define DIY_UNSUPPORTED_MPI_CALL(name) \ + throw std::runtime_error("`" #name "` not supported when DIY_NO_MPI is defined."); + +/* define operations */ +using MPI_Op = int; +static const MPI_Op MPI_MAX = 0; +static const MPI_Op MPI_MIN = 0; +static const MPI_Op MPI_SUM = 0; +static const MPI_Op MPI_PROD = 0; +static const MPI_Op MPI_LAND = 0; +static const MPI_Op MPI_LOR = 0; + +/* mpi i/o stuff */ +using MPI_Offset = size_t; +using MPI_File = int; +static const MPI_File MPI_FILE_NULL = 0; + +static const int MPI_MODE_CREATE = 1; +static const int MPI_MODE_RDONLY = 2; +static const int MPI_MODE_WRONLY = 4; +static const int MPI_MODE_RDWR = 8; +static const int MPI_MODE_DELETE_ON_CLOSE = 16; +static const int MPI_MODE_UNIQUE_OPEN = 32; +static const int MPI_MODE_EXCL = 64; +static const int MPI_MODE_APPEND = 128; +static const int MPI_MODE_SEQUENTIAL = 256; diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/point-to-point.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/point-to-point.hpp index dc8a341dc..f7b5b18f9 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/point-to-point.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/point-to-point.hpp @@ -15,11 +15,16 @@ namespace detail { void operator()(MPI_Comm comm, int dest, int tag, const T& x) const { +#ifndef DIY_NO_MPI typedef mpi_datatype Datatype; MPI_Send((void*) Datatype::address(x), Datatype::count(x), Datatype::datatype(), dest, tag, comm); +#else + (void) comm; (void) dest; (void) tag; (void) x; + DIY_UNSUPPORTED_MPI_CALL(MPI_Send); +#endif } }; @@ -32,6 +37,7 @@ namespace detail { status operator()(MPI_Comm comm, int source, int tag, T& x) const { +#ifndef DIY_NO_MPI typedef mpi_datatype Datatype; status s; MPI_Recv((void*) Datatype::address(x), @@ -39,6 +45,10 @@ namespace detail Datatype::datatype(), source, tag, comm, &s.s); return s; +#else + (void) comm; (void) source; (void) tag; (void) x; + DIY_UNSUPPORTED_MPI_CALL(MPI_Recv); +#endif } }; @@ -47,12 +57,17 @@ namespace detail { status operator()(MPI_Comm comm, int source, int tag, std::vector& x) const { +#ifndef DIY_NO_MPI status s; MPI_Probe(source, tag, comm, &s.s); x.resize(s.count()); - MPI_Recv(&x[0], x.size(), get_mpi_datatype(), source, tag, comm, &s.s); + MPI_Recv(&x[0], static_cast(x.size()), get_mpi_datatype(), source, tag, comm, &s.s); return s; +#else + (void) comm; (void) source; (void) tag; (void) x; + DIY_UNSUPPORTED_MPI_CALL(MPI_Recv); +#endif } }; @@ -65,6 +80,7 @@ namespace detail { request operator()(MPI_Comm comm, int dest, int tag, const T& x) const { +#ifndef DIY_NO_MPI request r; typedef mpi_datatype Datatype; MPI_Isend((void*) Datatype::address(x), @@ -72,6 +88,10 @@ namespace detail Datatype::datatype(), dest, tag, comm, &r.r); return r; +#else + (void) comm; (void) dest; (void) tag; (void) x; + DIY_UNSUPPORTED_MPI_CALL(MPI_Isend); +#endif } }; @@ -84,6 +104,7 @@ namespace detail { request operator()(MPI_Comm comm, int source, int tag, T& x) const { +#ifndef DIY_NO_MPI request r; typedef mpi_datatype Datatype; MPI_Irecv(Datatype::address(x), @@ -91,6 +112,10 @@ namespace detail Datatype::datatype(), source, tag, comm, &r.r); return r; +#else + (void) comm; (void) source; (void) tag; (void) x; + DIY_UNSUPPORTED_MPI_CALL(MPI_Irecv); +#endif } }; } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/request.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/request.hpp index 23b11816e..b4f999cad 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/request.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/request.hpp @@ -4,23 +4,47 @@ namespace mpi { struct request { - status wait() { status s; MPI_Wait(&r, &s.s); return s; } + inline + status wait(); inline optional test(); - void cancel() { MPI_Cancel(&r); } + inline + void cancel(); MPI_Request r; }; } } +diy::mpi::status +diy::mpi::request::wait() +{ +#ifndef DIY_NO_MPI + status s; + MPI_Wait(&r, &s.s); + return s; +#else + DIY_UNSUPPORTED_MPI_CALL(diy::mpi::request::wait); +#endif +} + diy::mpi::optional diy::mpi::request::test() { +#ifndef DIY_NO_MPI status s; int flag; MPI_Test(&r, &flag, &s.s); if (flag) return s; +#endif return optional(); } + +void +diy::mpi::request::cancel() +{ +#ifndef DIY_NO_MPI + MPI_Cancel(&r); +#endif +} diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/status.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/status.hpp index aab500c31..e90978bd4 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/status.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/mpi/status.hpp @@ -7,7 +7,9 @@ namespace mpi int source() const { return s.MPI_SOURCE; } int tag() const { return s.MPI_TAG; } int error() const { return s.MPI_ERROR; } - bool cancelled() const { int flag; MPI_Test_cancelled(const_cast(&s), &flag); return flag; } + + inline + bool cancelled() const; template int count() const; @@ -20,11 +22,28 @@ namespace mpi } } + +bool +diy::mpi::status::cancelled() const +{ +#ifndef DIY_NO_MPI + int flag; + MPI_Test_cancelled(const_cast(&s), &flag); + return flag; +#else + DIY_UNSUPPORTED_MPI_CALL(diy::mpi::status::cancelled); +#endif +} + template int diy::mpi::status::count() const { +#ifndef DIY_NO_MPI int c; MPI_Get_count(const_cast(&s), detail::get_mpi_datatype(), &c); return c; +#else + DIY_UNSUPPORTED_MPI_CALL(diy::mpi::status::count); +#endif } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/all-reduce.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/all-reduce.hpp index e34066595..41023445b 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/all-reduce.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/all-reduce.hpp @@ -45,7 +45,7 @@ struct RegularAllReducePartners: public RegularMergePartners //! returns whether a given block in a given round has dropped out of the merge yet or not inline bool active(int round, int gid, const Master& m) const { return Parent::active(parent_round(round), gid, m); } //! returns what the current round would be in the first or second parent merge reduction - int parent_round(int round) const { return round < (int) Parent::rounds() ? round : rounds() - round; } + int parent_round(int round) const { return round < (int) Parent::rounds() ? round : static_cast(rounds()) - round; } // incoming is only valid for an active gid; it will only be called with an active gid inline void incoming(int round, int gid, std::vector& partners, const Master& m) const diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/common.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/common.hpp index 43f8297a0..0913192bd 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/common.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/common.hpp @@ -113,7 +113,7 @@ fill(int round, int gid, std::vector& partners) const { partner += step; coords[kv.dim] = partner; - int partner_gid = Decomposer::coords_to_gid(coords, divisions_); + partner_gid = Decomposer::coords_to_gid(coords, divisions_); partners.push_back(partner_gid); } } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/swap.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/swap.hpp index cc3b3e494..be11ce928 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/swap.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/partners/swap.hpp @@ -32,7 +32,7 @@ struct RegularSwapPartners: public RegularPartners ): Parent(divs, kvs, contiguous) {} - bool active(int round, int gid, const Master&) const { return true; } // in swap-reduce every block is always active + bool active(int, int, const Master&) const { return true; } // in swap-reduce every block is always active void incoming(int round, int gid, std::vector& partners, const Master&) const { Parent::fill(round - 1, gid, partners); } void outgoing(int round, int gid, std::vector& partners, const Master&) const { Parent::fill(round, gid, partners); } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce-operations.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce-operations.hpp index 629824da5..a0799794d 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce-operations.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce-operations.hpp @@ -22,6 +22,7 @@ all_to_all(Master& master, //!< block owner ) { auto scoped = master.prof.scoped("all_to_all"); + (void)scoped; RegularDecomposer decomposer(1, interval(0,assigner.nblocks()-1), assigner.nblocks()); RegularSwapPartners partners(decomposer, k, false); reduce(master, assigner, partners, detail::AllToAllReduce(op, assigner), detail::SkipIntermediate(partners.rounds())); diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce.hpp index 6d47d7930..0dac8327f 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/reduce.hpp @@ -95,7 +95,7 @@ namespace detail struct ReduceNeverSkip { - bool operator()(int round, int lid, const Master& master) const { return false; } + bool operator()(int, int, const Master&) const { return false; } }; } @@ -133,7 +133,7 @@ void reduce(Master& master, //!< master object { std::vector incoming_gids; partners.incoming(round + 1, master.gid(i), incoming_gids, master); - expected += incoming_gids.size(); + expected += static_cast(incoming_gids.size()); master.incoming(master.gid(i)).clear(); } } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/serialization.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/serialization.hpp index 25640255d..828753548 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/serialization.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/serialization.hpp @@ -186,7 +186,8 @@ namespace diy { size_t s = v.size(); diy::save(bb, s); - diy::save(bb, &v[0], v.size()); + if (s > 0) + diy::save(bb, &v[0], v.size()); } static void load(BinaryBuffer& bb, Vector& v) @@ -194,7 +195,8 @@ namespace diy size_t s; diy::load(bb, s); v.resize(s); - diy::load(bb, &v[0], s); + if (s > 0) + diy::load(bb, &v[0], s); } }; @@ -207,7 +209,8 @@ namespace diy { size_t s = v.size(); diy::save(bb, s); - diy::save(bb, &v[0], v.size()); + if (s > 0) + diy::save(bb, &v[0], v.size()); } static void load(BinaryBuffer& bb, ValArray& v) @@ -215,7 +218,8 @@ namespace diy size_t s; diy::load(bb, s); v.resize(s); - diy::load(bb, &v[0], s); + if (s > 0) + diy::load(bb, &v[0], s); } }; @@ -413,12 +417,15 @@ diy::MemoryBuffer:: save_binary(const char* x, size_t count) { if (position + count > buffer.capacity()) - buffer.reserve((position + count) * growth_multiplier()); // if we have to grow, grow geometrically + { + double newsize = static_cast(position + count) * growth_multiplier(); // if we have to grow, grow geometrically + buffer.reserve(static_cast(newsize)); + } if (position + count > buffer.size()) buffer.resize(position + count); - std::copy(x, x + count, &buffer[position]); + std::copy_n(x, count, &buffer[position]); position += count; } @@ -426,7 +433,7 @@ void diy::MemoryBuffer:: load_binary(char* x, size_t count) { - std::copy(&buffer[position], &buffer[position + count], x); + std::copy_n(&buffer[position], count, x); position += count; } @@ -434,7 +441,7 @@ void diy::MemoryBuffer:: load_binary_back(char* x, size_t count) { - std::copy(&buffer[buffer.size() - count], &buffer[buffer.size()], x); + std::copy_n(&buffer[buffer.size() - count], count, x); buffer.resize(buffer.size() - count); } @@ -448,7 +455,7 @@ copy(MemoryBuffer& from, MemoryBuffer& to) size_t total = sizeof(size_t) + sz; to.buffer.resize(to.position + total); - std::copy(&from.buffer[from.position], &from.buffer[from.position + total], &to.buffer[to.position]); + std::copy_n(&from.buffer[from.position], total, &to.buffer[to.position]); to.position += total; from.position += total; } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/storage.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/storage.hpp index 62213b2c5..c2f13e5c9 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/storage.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/storage.hpp @@ -4,15 +4,12 @@ #include #include #include - -#include // mkstemp() on Mac -#include // mkstemp() on Linux -#include // remove() #include #include "serialization.hpp" #include "thread.hpp" #include "log.hpp" +#include "io/utils.hpp" namespace diy { @@ -75,11 +72,14 @@ namespace diy log->debug("FileStorage::put(): {}; buffer size: {}", filename, bb.size()); size_t sz = bb.buffer.size(); +#if defined(_WIN32) + size_t written = _write(fh, &bb.buffer[0], static_cast(sz)); +#else size_t written = write(fh, &bb.buffer[0], sz); +#endif if (written < sz || written == (size_t)-1) log->warn("Could not write the full buffer to {}: written = {}; size = {}", filename, written, sz); - fsync(fh); - close(fh); + io::utils::close(fh); bb.wipe(); #if 0 // double-check the written file size: only for extreme debugging @@ -98,12 +98,15 @@ namespace diy { std::string filename; int fh = open_random(filename); - +#if defined(_WIN32) + detail::FileBuffer fb(_fdopen(fh, "wb")); +#else detail::FileBuffer fb(fdopen(fh, "w")); +#endif save(x, fb); size_t sz = fb.size(); fclose(fb.file); - fsync(fh); + io::utils::sync(fh); return make_file_record(filename, sz); } @@ -116,10 +119,15 @@ namespace diy bb.buffer.reserve(fr.size + extra); bb.buffer.resize(fr.size); +#if defined(_WIN32) + int fh = -1; + _sopen_s(&fh, fr.name.c_str(), _O_RDONLY | _O_BINARY, _SH_DENYNO, _S_IREAD); + _read(fh, &bb.buffer[0], static_cast(fr.size)); +#else int fh = open(fr.name.c_str(), O_RDONLY | O_SYNC, 0600); read(fh, &bb.buffer[0], fr.size); - close(fh); - +#endif + io::utils::close(fh); remove_file(fr); } @@ -128,8 +136,14 @@ namespace diy FileRecord fr = extract_file_record(i); //int fh = open(fr.name.c_str(), O_RDONLY | O_SYNC, 0600); +#if defined(_WIN32) + int fh = -1; + _sopen_s(&fh, fr.name.c_str(), _O_RDONLY | _O_BINARY, _SH_DENYNO, _S_IREAD); + detail::FileBuffer fb(_fdopen(fh, "rb")); +#else int fh = open(fr.name.c_str(), O_RDONLY, 0600); detail::FileBuffer fb(fdopen(fh, "r")); +#endif load(x, fb); fclose(fb.file); @@ -144,7 +158,7 @@ namespace diy fr = (*accessor)[i]; accessor->erase(i); } - remove(fr.name.c_str()); + io::utils::remove(fr.name); (*current_size_.access()) -= fr.size; } @@ -158,7 +172,7 @@ namespace diy it != filenames_.const_access()->end(); ++it) { - remove(it->second.name.c_str()); + io::utils::remove(it->second.name); } } @@ -172,13 +186,7 @@ namespace diy // pick a template at random (very basic load balancing mechanism) filename = filename_templates_[std::rand() % filename_templates_.size()].c_str(); } -#ifdef __MACH__ - // TODO: figure out how to open with O_SYNC - int fh = mkstemp(const_cast(filename.c_str())); -#else - int fh = mkostemp(const_cast(filename.c_str()), O_WRONLY | O_SYNC); -#endif - + int fh = diy::io::utils::mkstemp(filename); return fh; } @@ -208,7 +216,7 @@ namespace diy void remove_file(const FileRecord& fr) { - remove(fr.name.c_str()); + io::utils::remove(fr.name); (*current_size_.access()) -= fr.size; } diff --git a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/time.hpp b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/time.hpp index d6b44c2e1..cb4cc8e24 100644 --- a/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/time.hpp +++ b/vtkm/thirdparty/diy/vtkmdiy/include/vtkmdiy/time.hpp @@ -1,12 +1,13 @@ #ifndef DIY_TIME_HPP #define DIY_TIME_HPP +#ifndef _WIN32 #include - #ifdef __MACH__ #include #include -#endif +#endif // __MACH__ +#endif // ifndef _WIN32 namespace diy { @@ -21,11 +22,20 @@ inline time_type get_time() host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &ts); mach_port_deallocate(mach_task_self(), cclock); + return ts.tv_sec*1000 + ts.tv_nsec/1000000; +#elif defined(_WIN32) + // SOURCE: http://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows + __int64 wintime; + GetSystemTimeAsFileTime((FILETIME*)&wintime); + wintime -=116444736000000000i64; //1jan1601 to 1jan1970 + long tv_sec = static_cast(wintime / 10000000i64); //seconds + long tv_nsec = static_cast(wintime % 10000000i64 *100); //nano-seconds + return static_cast(tv_sec*1000 + tv_nsec/1000000); #else timespec ts; clock_gettime(CLOCK_REALTIME, &ts); -#endif return ts.tv_sec*1000 + ts.tv_nsec/1000000; +#endif } } diff --git a/vtkm/worklet/AverageByKey.h b/vtkm/worklet/AverageByKey.h index 99129ac7a..b4e816a70 100644 --- a/vtkm/worklet/AverageByKey.h +++ b/vtkm/worklet/AverageByKey.h @@ -109,7 +109,7 @@ struct AverageByKey template VTKM_EXEC void operator()(const ValueType& v, const vtkm::Id& count, ValueType& vout) const { - typedef typename VecTraits::ComponentType ComponentType; + using ComponentType = typename VecTraits::ComponentType; vout = v * ComponentType(1. / static_cast(count)); } @@ -143,10 +143,10 @@ struct AverageByKey vtkm::cont::ArrayHandle& outputValueArray, DeviceAdapter) { - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; - typedef vtkm::cont::ArrayHandle ValueInArray; - typedef vtkm::cont::ArrayHandle IdArray; - typedef vtkm::cont::ArrayHandle ValueArray; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + using ValueInArray = vtkm::cont::ArrayHandle; + using IdArray = vtkm::cont::ArrayHandle; + using ValueArray = vtkm::cont::ArrayHandle; // sort the indexed array vtkm::cont::ArrayHandleIndex indexArray(keyArray.GetNumberOfValues()); @@ -158,12 +158,12 @@ struct AverageByKey Algorithm::SortByKey(keyArraySorted, indexArraySorted, vtkm::SortLess()); // generate permultation array based on the indexes - typedef vtkm::cont::ArrayHandlePermutation PermutatedValueArray; + using PermutatedValueArray = vtkm::cont::ArrayHandlePermutation; PermutatedValueArray valueArraySorted = vtkm::cont::make_ArrayHandlePermutation(indexArraySorted, valueArray); // reduce both sumArray and countArray by key - typedef vtkm::cont::ArrayHandleConstant ConstIdArray; + using ConstIdArray = vtkm::cont::ArrayHandleConstant; ConstIdArray constOneArray(1, valueArray.GetNumberOfValues()); IdArray countArray; ValueArray sumArray; diff --git a/vtkm/worklet/CMakeLists.txt b/vtkm/worklet/CMakeLists.txt index e442d55b3..8bda9768e 100644 --- a/vtkm/worklet/CMakeLists.txt +++ b/vtkm/worklet/CMakeLists.txt @@ -54,7 +54,9 @@ set(headers ParticleAdvection.h PointAverage.h PointElevation.h + Probe.h RemoveUnusedPoints.h + ScalarsToColors.h ScatterCounting.h ScatterIdentity.h ScatterPermutation.h @@ -74,6 +76,12 @@ set(headers WorkletReduceByKey.h ) + +set(header_impls + ScalarsToColors.hxx + ) + + #----------------------------------------------------------------------------- add_subdirectory(internal) add_subdirectory(contour) @@ -88,6 +96,7 @@ add_subdirectory(wavelets) add_subdirectory(particleadvection) vtkm_declare_headers(${headers}) +vtkm_declare_headers(${header_impls} TESTABLE OFF) #----------------------------------------------------------------------------- diff --git a/vtkm/worklet/CellAverage.h b/vtkm/worklet/CellAverage.h index 96544e6af..4072f5e8c 100644 --- a/vtkm/worklet/CellAverage.h +++ b/vtkm/worklet/CellAverage.h @@ -38,7 +38,7 @@ public: FieldInPoint<> inPoints, FieldOutCell<> outCells); typedef void ExecutionSignature(PointCount, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::IdComponent& numPoints, diff --git a/vtkm/worklet/Clip.h b/vtkm/worklet/Clip.h index 025abcf7b..ab1d8aa6d 100644 --- a/vtkm/worklet/Clip.h +++ b/vtkm/worklet/Clip.h @@ -70,15 +70,14 @@ template class ExecutionConnectivityExplicit : vtkm::exec::ExecutionObjectBase { private: - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - UInt8Portal; + using UInt8Portal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::Portal IdComponentPortal; + using IdComponentPortal = typename vtkm::cont::ArrayHandle< + vtkm::IdComponent>::template ExecutionTypes::Portal; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - IdPortal; + using IdPortal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; public: VTKM_CONT @@ -134,9 +133,9 @@ private: struct ClipStats { - vtkm::Id NumberOfCells; - vtkm::Id NumberOfIndices; - vtkm::Id NumberOfNewPoints; + vtkm::Id NumberOfCells = 0; + vtkm::Id NumberOfIndices = 0; + vtkm::Id NumberOfNewPoints = 0; struct SumOp { @@ -154,8 +153,9 @@ struct ClipStats struct EdgeInterpolation { - vtkm::Id Vertex1, Vertex2; - vtkm::Float64 Weight; + vtkm::Id Vertex1 = -1; + vtkm::Id Vertex2 = -1; + vtkm::Float64 Weight = 0; struct LessThanOp { @@ -186,7 +186,7 @@ public: template class ComputeStats : public vtkm::worklet::WorkletMapPointToCell { - typedef internal::ClipTables::DevicePortal ClipTablesPortal; + using ClipTablesPortal = internal::ClipTables::DevicePortal; public: typedef void ControlSignature(CellSetIn cellset, @@ -249,7 +249,7 @@ public: template class GenerateCellSet : public vtkm::worklet::WorkletMapPointToCell { - typedef internal::ClipTables::DevicePortal ClipTablesPortal; + using ClipTablesPortal = internal::ClipTables::DevicePortal; public: struct EdgeInterp : vtkm::ListTagBase @@ -317,7 +317,7 @@ public: { connectivityExplicit.SetConnectivity(connectivityIdx++, indices[entry - 100]); } - else // edge, new point to be generated by cutting the egde + else // edge, new point to be generated by cutting the edge { internal::ClipTables::EdgeVec edge = this->ClipTables.GetEdge(shape.Id, entry); // Sanity check to make sure the edge is valid. @@ -363,13 +363,12 @@ public: template class AmendConnectivity : public vtkm::exec::FunctorBase { - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - IdPortal; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst IdPortalConst; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst EdgeInterpolationPortalConst; + using IdPortal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; + using IdPortalConst = typename vtkm::cont::ArrayHandle::template ExecutionTypes< + DeviceAdapter>::PortalConst; + using EdgeInterpolationPortalConst = typename vtkm::cont::ArrayHandle< + EdgeInterpolation>::template ExecutionTypes::PortalConst; public: VTKM_CONT @@ -435,9 +434,9 @@ public: vtkm::Float64 value, DeviceAdapter device) { - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; - typedef internal::ClipTables::DevicePortal ClipTablesPortal; + using ClipTablesPortal = internal::ClipTables::DevicePortal; ClipTablesPortal clipTablesDevicePortal = this->ClipTablesInstance.GetDevicePortal(device); // Step 1. compute counts for the elements of the cell set data structure @@ -449,7 +448,7 @@ public: .Invoke(cellSet, scalars, clipTableIdxs, stats); // compute offsets for each invocation - ClipStats zero = { 0, 0, 0 }; + ClipStats zero; vtkm::cont::ArrayHandle cellSetIndices; ClipStats total = Algorithm::ScanExclusive(stats, cellSetIndices, ClipStats::SumOp(), zero); stats.ReleaseResources(); @@ -574,11 +573,11 @@ public: class Kernel : public vtkm::exec::FunctorBase { public: - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - FieldPortal; + using FieldPortal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst EdgeInterpolationPortalConst; + using EdgeInterpolationPortalConst = typename vtkm::cont::ArrayHandle< + EdgeInterpolation>::template ExecutionTypes::PortalConst; VTKM_CONT Kernel(EdgeInterpolationPortalConst interpolation, @@ -619,7 +618,7 @@ public: template VTKM_CONT void operator()(const vtkm::cont::ArrayHandle& field) const { - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; vtkm::Id count = this->InterpolationArray.GetNumberOfValues(); diff --git a/vtkm/worklet/DispatcherMapField.h b/vtkm/worklet/DispatcherMapField.h index b79c8fc42..14356a0e9 100644 --- a/vtkm/worklet/DispatcherMapField.h +++ b/vtkm/worklet/DispatcherMapField.h @@ -37,10 +37,10 @@ class DispatcherMapField WorkletType, vtkm::worklet::WorkletMapField> { - typedef vtkm::worklet::internal::DispatcherBase, - WorkletType, - vtkm::worklet::WorkletMapField> - Superclass; + using Superclass = + vtkm::worklet::internal::DispatcherBase, + WorkletType, + vtkm::worklet::WorkletMapField>; public: VTKM_CONT @@ -53,7 +53,7 @@ public: VTKM_CONT void DoInvoke(const Invocation& invocation) const { // This is the type for the input domain - typedef typename Invocation::InputDomainType InputDomainType; + using InputDomainType = typename Invocation::InputDomainType; // We can pull the input domain parameter (the data specifying the input // domain) from the invocation object. diff --git a/vtkm/worklet/DispatcherMapTopology.h b/vtkm/worklet/DispatcherMapTopology.h index ad1d2ade2..f7fbffd65 100644 --- a/vtkm/worklet/DispatcherMapTopology.h +++ b/vtkm/worklet/DispatcherMapTopology.h @@ -38,10 +38,10 @@ class DispatcherMapTopology WorkletType, vtkm::worklet::detail::WorkletMapTopologyBase> { - typedef vtkm::worklet::internal::DispatcherBase, - WorkletType, - vtkm::worklet::detail::WorkletMapTopologyBase> - Superclass; + using Superclass = + vtkm::worklet::internal::DispatcherBase, + WorkletType, + vtkm::worklet::detail::WorkletMapTopologyBase>; public: VTKM_CONT @@ -54,7 +54,7 @@ public: VTKM_CONT void DoInvoke(const Invocation& invocation) const { // This is the type for the input domain - typedef typename Invocation::InputDomainType InputDomainType; + using InputDomainType = typename Invocation::InputDomainType; // If you get a compile error on this line, then you have tried to use // something that is not a vtkm::cont::CellSet as the input domain to a diff --git a/vtkm/worklet/DispatcherStreamingMapField.h b/vtkm/worklet/DispatcherStreamingMapField.h index 0ece969de..2fe7fc356 100644 --- a/vtkm/worklet/DispatcherStreamingMapField.h +++ b/vtkm/worklet/DispatcherStreamingMapField.h @@ -59,21 +59,21 @@ struct DispatcherStreamingMapFieldTransformFunctor template struct DetermineReturnType { - typedef vtkm::cont::ArrayHandleStreaming type; + using type = vtkm::cont::ArrayHandleStreaming; }; template struct DetermineReturnType { - typedef NotArrayHandleType type; + using type = NotArrayHandleType; }; template struct ReturnType { - typedef typename DetermineReturnType< + using type = typename DetermineReturnType< ParameterType, - vtkm::cont::internal::ArrayHandleCheck::type::value>::type type; + vtkm::cont::internal::ArrayHandleCheck::type::value>::type; }; template @@ -125,7 +125,7 @@ struct DispatcherStreamingMapFieldTransferFunctor template struct ReturnType { - typedef ParameterType type; + using type = ParameterType; }; template @@ -169,10 +169,10 @@ class DispatcherStreamingMapField WorkletType, vtkm::worklet::WorkletMapField> { - typedef vtkm::worklet::internal::DispatcherBase, - WorkletType, - vtkm::worklet::WorkletMapField> - Superclass; + using Superclass = + vtkm::worklet::internal::DispatcherBase, + WorkletType, + vtkm::worklet::WorkletMapField>; public: VTKM_CONT @@ -202,7 +202,7 @@ public: VTKM_CONT void DoInvoke(const Invocation& invocation) const { // This is the type for the input domain - typedef typename Invocation::InputDomainType InputDomainType; + using InputDomainType = typename Invocation::InputDomainType; // We can pull the input domain parameter (the data specifying the input // domain) from the invocation object. @@ -217,12 +217,12 @@ public: if (fullSize % NumberOfBlocks != 0) blockSize += 1; - typedef detail:: - DispatcherStreamingMapFieldTransformFunctor - TransformFunctorType; - typedef detail:: - DispatcherStreamingMapFieldTransferFunctor - TransferFunctorType; + using TransformFunctorType = + detail::DispatcherStreamingMapFieldTransformFunctor; + using TransferFunctorType = + detail::DispatcherStreamingMapFieldTransferFunctor; for (vtkm::Id block = 0; block < NumberOfBlocks; block++) { @@ -232,20 +232,19 @@ public: numberOfInstances = fullSize - blockSize * block; vtkm::Id globalIndexOffset = blockSize * block; - typedef typename Invocation::ParameterInterface ParameterInterfaceType; - typedef - typename ParameterInterfaceType::template StaticTransformType::type - ReportedType; + using ParameterInterfaceType = typename Invocation::ParameterInterface; + using ReportedType = + typename ParameterInterfaceType::template StaticTransformType::type; ReportedType newParams = invocation.Parameters.StaticTransformCont( TransformFunctorType(block, blockSize, numberOfInstances, fullSize)); - typedef typename Invocation::template ChangeParametersType::type ChangedType; + using ChangedType = typename Invocation::template ChangeParametersType::type; ChangedType changedParams = invocation.ChangeParameters(newParams); this->BasicInvoke(changedParams, numberOfInstances, globalIndexOffset, Device()); // Loop over parameters again to sync results for this block into control array - typedef typename ChangedType::ParameterInterface ParameterInterfaceType2; + using ParameterInterfaceType2 = typename ChangedType::ParameterInterface; const ParameterInterfaceType2& parameters2 = changedParams.Parameters; parameters2.StaticTransformCont(TransferFunctorType()); } @@ -262,17 +261,15 @@ private: const OutputRangeType& outputRange, DeviceAdapter device) const { - typedef typename Invocation::ParameterInterface ParameterInterfaceType; + using ParameterInterfaceType = typename Invocation::ParameterInterface; const ParameterInterfaceType& parameters = invocation.Parameters; - typedef vtkm::worklet::internal::detail::DispatcherBaseTransportFunctor< + using TransportFunctorType = vtkm::worklet::internal::detail::DispatcherBaseTransportFunctor< typename Invocation::ControlInterface, typename Invocation::InputDomainType, - DeviceAdapter> - TransportFunctorType; - typedef - typename ParameterInterfaceType::template StaticTransformType::type - ExecObjectParameters; + DeviceAdapter>; + using ExecObjectParameters = + typename ParameterInterfaceType::template StaticTransformType::type; ExecObjectParameters execObjectParameters = parameters.StaticTransformCont( TransportFunctorType(invocation.GetInputDomain(), inputRange, outputRange)); diff --git a/vtkm/worklet/ExternalFaces.h b/vtkm/worklet/ExternalFaces.h index 05b8cf81d..c0e89b41a 100644 --- a/vtkm/worklet/ExternalFaces.h +++ b/vtkm/worklet/ExternalFaces.h @@ -62,7 +62,7 @@ struct ExternalFaces FieldOut<> numFacesInCell, FieldInPoint pointCoordinates); typedef _2 ExecutionSignature(CellShape, _3); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_CONT NumExternalFacesPerStructuredCell(const vtkm::Vec& min_point, @@ -137,7 +137,7 @@ struct ExternalFaces FieldOut<> faceConnectivity, FieldInPoint pointCoordinates); typedef void ExecutionSignature(CellShape, VisitIndex, InputIndex, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; using ScatterType = vtkm::worklet::ScatterCounting; @@ -334,7 +334,7 @@ struct ExternalFaces public: typedef void ControlSignature(CellSetIn inCellSet, FieldOut<> numFacesInCell); typedef _2 ExecutionSignature(CellShape); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC vtkm::IdComponent operator()(CellShapeTag shape) const @@ -352,7 +352,7 @@ struct ExternalFaces FieldOut<> originCells, FieldOut<> originFaces); typedef void ExecutionSignature(_2, _3, _4, CellShape, FromIndices, InputIndex, VisitIndex); - typedef _1 InputDomain; + using InputDomain = _1; using ScatterType = vtkm::worklet::ScatterCounting; @@ -631,7 +631,7 @@ public: public: typedef void ControlSignature(CellSetIn inCellSet, FieldOut<> isPolyDataCell); typedef _2 ExecutionSignature(CellShape); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC vtkm::IdComponent operator()(CellShapeTag shape) const @@ -663,7 +663,7 @@ public: typedef void ControlSignature(CellSetIn inCellSet, FieldOut<> numPoints); typedef _2 ExecutionSignature(PointCount); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_EXEC vtkm::Id operator()(vtkm::Id count) const { return count; } private: @@ -792,12 +792,12 @@ public: vtkm::Id3 PointDimensions = inCellSet.GetPointDimensions(); - typedef vtkm::cont::ArrayHandle DefaultHandle; - typedef vtkm::cont::ArrayHandleCartesianProduct - CartesianArrayHandle; + using DefaultHandle = vtkm::cont::ArrayHandle; + using CartesianArrayHandle = + vtkm::cont::ArrayHandleCartesianProduct; auto coordData = coord.GetData(); - if (coordData.IsSameType()) + if (coordData.IsType()) { auto vertices = coordData.Cast(); @@ -837,7 +837,7 @@ public: numExternalFacesDispatcher.Invoke(inCellSet, numExternalFaces, coordData); - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::Id numberOfExternalFaces = DeviceAlgorithms::Reduce(numExternalFaces, 0, vtkm::Sum()); vtkm::worklet::ScatterCounting scatterCellToExternalFace(numExternalFaces, DeviceAdapter()); @@ -1017,7 +1017,7 @@ public: else { // Join poly data to face data output - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandleConcatenate faceShapesArray( faceShapes, polyDataShapes); @@ -1035,8 +1035,8 @@ public: DeviceAlgorithm::Copy(connectivityArray, joinedConnectivity); // Adjust poly data offsets array with face connectivity size before join - typedef vtkm::cont::ArrayHandleTransform> - TransformBiasArrayType; + using TransformBiasArrayType = + vtkm::cont::ArrayHandleTransform>; TransformBiasArrayType adjustedPolyDataOffsets = vtkm::cont::make_ArrayHandleTransform( polyDataOffsets, BiasFunctor(faceConnectivity.GetNumberOfValues())); diff --git a/vtkm/worklet/ExtractGeometry.h b/vtkm/worklet/ExtractGeometry.h index c744d61a8..6af03c3c7 100644 --- a/vtkm/worklet/ExtractGeometry.h +++ b/vtkm/worklet/ExtractGeometry.h @@ -142,8 +142,8 @@ public: const vtkm::cont::ArrayHandle& cellIds, DeviceAdapter) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; - typedef vtkm::cont::CellSetPermutation OutputType; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; + using OutputType = vtkm::cont::CellSetPermutation; DeviceAlgorithm::Copy(cellIds, this->ValidCellIds); diff --git a/vtkm/worklet/ExtractPoints.h b/vtkm/worklet/ExtractPoints.h index fb0a7f54e..0f8dd5c84 100644 --- a/vtkm/worklet/ExtractPoints.h +++ b/vtkm/worklet/ExtractPoints.h @@ -81,7 +81,7 @@ public: const vtkm::cont::ArrayHandle& pointIds, DeviceAdapter) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; DeviceAlgorithm::Copy(pointIds, this->ValidPointIds); // Make CellSetSingleType with VERTEX at each point id @@ -101,7 +101,7 @@ public: bool extractInside, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // Worklet output will be a boolean passFlag array vtkm::cont::ArrayHandle passFlags; diff --git a/vtkm/worklet/FieldEntropy.h b/vtkm/worklet/FieldEntropy.h index 7e9913db0..2aa3fd2e9 100644 --- a/vtkm/worklet/FieldEntropy.h +++ b/vtkm/worklet/FieldEntropy.h @@ -75,7 +75,7 @@ public: vtkm::Id numberOfBins, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; ///// calculate histogram using FieldHistogram worklet ///// vtkm::Range range; diff --git a/vtkm/worklet/FieldHistogram.h b/vtkm/worklet/FieldHistogram.h index 9045a29da..509d394fb 100644 --- a/vtkm/worklet/FieldHistogram.h +++ b/vtkm/worklet/FieldHistogram.h @@ -44,7 +44,7 @@ namespace template T compute_delta(T fieldMinValue, T fieldMaxValue, vtkm::Id num) { - typedef vtkm::VecTraits VecType; + using VecType = vtkm::VecTraits; const T fieldRange = fieldMaxValue - fieldMinValue; return fieldRange / static_cast(num); } @@ -69,7 +69,7 @@ public: public: typedef void ControlSignature(FieldIn<> value, FieldOut<> binIndex); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numberOfBins; FieldType minValue; @@ -102,7 +102,7 @@ public: WholeArrayIn counts, FieldOut outputCount); typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::Id& index, @@ -129,7 +129,7 @@ public: vtkm::cont::ArrayHandle& binArray, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; //todo: need to have a signature that can use an input range so we can //leverage fields that have already computed there range diff --git a/vtkm/worklet/FieldStatistics.h b/vtkm/worklet/FieldStatistics.h index ddcbc67ae..57532d8b0 100644 --- a/vtkm/worklet/FieldStatistics.h +++ b/vtkm/worklet/FieldStatistics.h @@ -71,7 +71,7 @@ public: FieldOut<> pow3Array, FieldOut<> pow4Array); typedef void ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numPowers; @@ -100,7 +100,7 @@ public: public: typedef void ControlSignature(FieldIn<> value, FieldOut<> diff); typedef _2 ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; FieldType constant; @@ -117,8 +117,8 @@ public: template void Run(vtkm::cont::ArrayHandle fieldArray, StatInfo& statinfo) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; - typedef typename vtkm::cont::ArrayHandle::PortalConstControl FieldPortal; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; + using FieldPortal = typename vtkm::cont::ArrayHandle::PortalConstControl; // Copy original data to array for sorting vtkm::cont::ArrayHandle tempArray; diff --git a/vtkm/worklet/KernelSplatter.h b/vtkm/worklet/KernelSplatter.h index f8ab96e00..c440773f9 100644 --- a/vtkm/worklet/KernelSplatter.h +++ b/vtkm/worklet/KernelSplatter.h @@ -73,9 +73,9 @@ namespace debug template void OutputArrayDebug(const vtkm::cont::ArrayHandle& outputArray, const std::string& name) { - typedef T ValueType; - typedef vtkm::cont::internal::Storage StorageType; - typedef typename StorageType::PortalConstType PortalConstType; + using ValueType = T; + using StorageType = vtkm::cont::internal::Storage; + using PortalConstType = typename StorageType::PortalConstType; PortalConstType readPortal = outputArray.GetPortalConstControl(); vtkm::cont::ArrayPortalToIterators iterators(readPortal); std::vector result(readPortal.GetNumberOfValues()); @@ -90,8 +90,8 @@ template void OutputArrayDebug(const vtkm::cont::ArrayHandle>& outputArray, const std::string& name) { - typedef T ValueType; - typedef typename vtkm::cont::ArrayHandle>::PortalConstControl PortalConstType; + using ValueType = T; + using PortalConstType = typename vtkm::cont::ArrayHandle>::PortalConstControl; PortalConstType readPortal = outputArray.GetPortalConstControl(); vtkm::cont::ArrayPortalToIterators iterators(readPortal); std::cout << name.c_str() << " " << outputArray.GetNumberOfValues() << "\n"; @@ -108,8 +108,8 @@ void OutputArrayDebug( outputArray, const std::string& name) { - typedef typename vtkm::cont::ArrayHandlePermutation>>:: - PortalConstControl PortalConstType; + using PortalConstType = typename vtkm::cont:: + ArrayHandlePermutation>>::PortalConstControl; PortalConstType readPortal = outputArray.GetPortalConstControl(); vtkm::cont::ArrayPortalToIterators iterators(readPortal); std::cout << name.c_str() << " " << outputArray.GetNumberOfValues() << "\n"; @@ -146,21 +146,21 @@ void OutputArrayDebug( template struct KernelSplatterFilterUniformGrid { - typedef vtkm::cont::ArrayHandle DoubleHandleType; - typedef vtkm::cont::ArrayHandle FloatHandleType; - typedef vtkm::cont::ArrayHandle VecHandleType; - typedef vtkm::cont::ArrayHandle IdHandleType; + using DoubleHandleType = vtkm::cont::ArrayHandle; + using FloatHandleType = vtkm::cont::ArrayHandle; + using VecHandleType = vtkm::cont::ArrayHandle; + using IdHandleType = vtkm::cont::ArrayHandle; // - typedef vtkm::Vec FloatVec; - typedef vtkm::Vec PointType; - typedef vtkm::cont::ArrayHandle PointHandleType; + using FloatVec = vtkm::Vec; + using PointType = vtkm::Vec; + using PointHandleType = vtkm::cont::ArrayHandle; // - typedef vtkm::cont::ArrayHandlePermutation VecPermType; - typedef vtkm::cont::ArrayHandlePermutation PointVecPermType; - typedef vtkm::cont::ArrayHandlePermutation IdPermType; - typedef vtkm::cont::ArrayHandlePermutation FloatPermType; + using VecPermType = vtkm::cont::ArrayHandlePermutation; + using PointVecPermType = vtkm::cont::ArrayHandlePermutation; + using IdPermType = vtkm::cont::ArrayHandlePermutation; + using FloatPermType = vtkm::cont::ArrayHandlePermutation; // - typedef vtkm::cont::ArrayHandleCounting IdCountingType; + using IdCountingType = vtkm::cont::ArrayHandleCounting; //----------------------------------------------------------------------- // zero an array, diff --git a/vtkm/worklet/MarchingCubes.h b/vtkm/worklet/MarchingCubes.h index a41411a84..945584e6a 100644 --- a/vtkm/worklet/MarchingCubes.h +++ b/vtkm/worklet/MarchingCubes.h @@ -122,7 +122,7 @@ public: FieldOutCell outNumTriangles, WholeArrayIn numTrianglesTable); typedef void ExecutionSignature(CellShape, _1, _2, _4, _5); - typedef _3 InputDomain; + using InputDomain = _3; template VTKM_EXEC void operator()(vtkm::CellShapeTagGeneric shape, @@ -182,11 +182,11 @@ class EdgeWeightGenerateMetaData template struct PortalTypes { - typedef vtkm::cont::ArrayHandle HandleType; - typedef typename HandleType::template ExecutionTypes ExecutionTypes; + using HandleType = vtkm::cont::ArrayHandle; + using ExecutionTypes = typename HandleType::template ExecutionTypes; - typedef typename ExecutionTypes::Portal Portal; - typedef typename ExecutionTypes::PortalConst PortalConst; + using Portal = typename ExecutionTypes::Portal; + using PortalConst = typename ExecutionTypes::PortalConst; }; public: @@ -233,7 +233,7 @@ public: { }; - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; typedef void ControlSignature( CellSetIn cellset, // Cell set @@ -243,7 +243,7 @@ public: typedef void ExecutionSignature(CellShape, _2, _3, InputIndex, WorkIndex, VisitIndex, FromIndices); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_CONT EdgeWeightGenerate(const EdgeWeightGenerateMetaData& meta) @@ -300,7 +300,7 @@ public: const IndicesVecType& indices) const { //covers when we have hexs coming from 3d structured data const vtkm::Id outputPointId = 3 * outputCellId; - typedef typename vtkm::VecTraits::ComponentType FieldType; + using FieldType = typename vtkm::VecTraits::ComponentType; vtkm::IdComponent sum = 0, caseNumber = 0; vtkm::IdComponent i = 0, size = static_cast(isovalues.GetNumberOfValues()); @@ -309,7 +309,7 @@ public: const FieldType ivalue = isovalues[i]; // Compute the Marching Cubes case number for this cell. We need to iterate // the isovalues until the sum >= our visit index. But we need to make - // sure the caseNumber is correct before stoping + // sure the caseNumber is correct before stopping caseNumber = ((fieldIn[0] > ivalue) | (fieldIn[1] > ivalue) << 1 | (fieldIn[2] > ivalue) << 2 | (fieldIn[3] > ivalue) << 3 | (fieldIn[4] > ivalue) << 4 | (fieldIn[5] > ivalue) << 5 | @@ -367,7 +367,7 @@ public: WholeArrayIn<> inputField, FieldOut<> output); typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_CONT MapPointField() {} @@ -417,7 +417,7 @@ struct MergeDuplicateValues : vtkm::worklet::WorkletReduceByKey ReducedValuesOut<> valueOut1, ReducedValuesOut<> valueOut2); typedef void ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; template , FieldOut<>); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_EXEC void operator()(const vtkm::Id2& input, vtkm::Id2& output) const { output = input; } diff --git a/vtkm/worklet/Mask.h b/vtkm/worklet/Mask.h index 339a6f11e..9dea59a20 100644 --- a/vtkm/worklet/Mask.h +++ b/vtkm/worklet/Mask.h @@ -48,8 +48,8 @@ public: const vtkm::Id stride, DeviceAdapter) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; - typedef vtkm::cont::CellSetPermutation OutputType; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; + using OutputType = vtkm::cont::CellSetPermutation; vtkm::Id numberOfInputCells = cellSet.GetNumberOfCells(); vtkm::Id numberOfSampledCells = numberOfInputCells / stride; diff --git a/vtkm/worklet/MaskPoints.h b/vtkm/worklet/MaskPoints.h index 0084afdd8..0556cf516 100644 --- a/vtkm/worklet/MaskPoints.h +++ b/vtkm/worklet/MaskPoints.h @@ -39,7 +39,7 @@ public: const vtkm::Id stride, DeviceAdapter) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::Id numberOfInputPoints = cellSet.GetNumberOfPoints(); vtkm::Id numberOfSampledPoints = numberOfInputPoints / stride; diff --git a/vtkm/worklet/NDimsEntropy.h b/vtkm/worklet/NDimsEntropy.h index cc20a2faf..a7d82aa76 100644 --- a/vtkm/worklet/NDimsEntropy.h +++ b/vtkm/worklet/NDimsEntropy.h @@ -66,7 +66,7 @@ public: template vtkm::Float64 Run(DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; std::vector> binIds; vtkm::cont::ArrayHandle freqs; diff --git a/vtkm/worklet/NDimsHistMarginalization.h b/vtkm/worklet/NDimsHistMarginalization.h index 7b431c2d0..4b77fb91f 100644 --- a/vtkm/worklet/NDimsHistMarginalization.h +++ b/vtkm/worklet/NDimsHistMarginalization.h @@ -73,7 +73,7 @@ public: vtkm::cont::ArrayHandle& marginalFreqs, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; //total variables vtkm::Id numOfVariable = static_cast(binId.size()); @@ -160,7 +160,7 @@ public: vtkm::cont::ArrayHandle& marginalFreqs, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; //total variables vtkm::Id numOfVariable = static_cast(binId.size()); @@ -172,7 +172,7 @@ public: vtkm::cont::ArrayHandle freqs; DeviceAlgorithms::Copy(freqsIn, freqs); - vtkm::Id numMarginalVariables = 0; //count num of marginal varaibles + vtkm::Id numMarginalVariables = 0; //count num of marginal variables for (vtkm::Id i = 0; i < numOfVariable; i++) { if (marginalVariables.GetPortalConstControl().Get(i) == true) diff --git a/vtkm/worklet/NDimsHistogram.h b/vtkm/worklet/NDimsHistogram.h index dad0da144..89ef282c9 100644 --- a/vtkm/worklet/NDimsHistogram.h +++ b/vtkm/worklet/NDimsHistogram.h @@ -46,7 +46,7 @@ public: template void SetNumOfDataPoints(vtkm::Id _numDataPoints, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; NumDataPoints = _numDataPoints; @@ -82,18 +82,18 @@ public: // Execute N-Dim histogram worklet to get N-Dims histogram from input fields // Input arguments: // binId: returned bin id of NDims-histogram, binId has n arrays, if length of fieldName is n - // freqs: returned frequncy(count) array + // freqs: returned frequency(count) array // Note: the ND-histogram is returned in the fashion of sparse representation. - // (no zero freqncy in freqs array) + // (no zero frequency in freqs array) // the length of all arrays in binId and freqs array must be the same // if the length of fieldNames is n (compute a n-dimensional hisotgram) - // freqs[i] is the freqncy of the bin with bin Ids{ binId[0][i], binId[1][i], ... binId[n-1][i] } + // freqs[i] is the frequency of the bin with bin Ids{ binId[0][i], binId[1][i], ... binId[n-1][i] } template void Run(std::vector>& binId, vtkm::cont::ArrayHandle& freqs, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = typename vtkm::cont::DeviceAdapterAlgorithm; binId.resize(NumberOfBins.size()); diff --git a/vtkm/worklet/ParticleAdvection.h b/vtkm/worklet/ParticleAdvection.h index d05dd8ffc..c08b15cec 100644 --- a/vtkm/worklet/ParticleAdvection.h +++ b/vtkm/worklet/ParticleAdvection.h @@ -168,7 +168,7 @@ public: const vtkm::Id& nSteps, const DeviceAdapter&) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::worklet::particleadvection::StreamlineWorklet worklet; diff --git a/vtkm/worklet/PointAverage.h b/vtkm/worklet/PointAverage.h index b477dae3f..64f653936 100644 --- a/vtkm/worklet/PointAverage.h +++ b/vtkm/worklet/PointAverage.h @@ -39,7 +39,7 @@ public: FieldInCell<> inCellField, FieldOutPoint<> outPointField); typedef void ExecutionSignature(CellCount, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::IdComponent& numCells, diff --git a/vtkm/worklet/Probe.h b/vtkm/worklet/Probe.h new file mode 100644 index 000000000..baa6d7390 --- /dev/null +++ b/vtkm/worklet/Probe.h @@ -0,0 +1,331 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#ifndef vtk_m_worklet_Probe_h +#define vtk_m_worklet_Probe_h + +#include +#include + +#include +#include +#include +#include + +#include + +namespace vtkm +{ +namespace worklet +{ + +class Probe +{ + //============================================================================ +private: + template + static vtkm::ListTagBase GetCellSetListTag(const CellSetType&) + { + return {}; + } + + template + static CellSetList GetCellSetListTag(const vtkm::cont::DynamicCellSetBase&) + { + return {}; + } + + template + void RunImpl(const CellSetType& cells, + const vtkm::cont::CoordinateSystem& coords, + const vtkm::cont::ArrayHandle& points, + Device device) + { + this->InputCellSet = vtkm::cont::DynamicCellSet(cells); + + vtkm::cont::CellLocator locator; + locator.SetCellSet(this->InputCellSet); + locator.SetCoordinates(coords); + locator.Build(device); + locator.FindCells( + points, this->CellIds, this->ParametricCoordinates, device, GetCellSetListTag(cells)); + } + + //============================================================================ +public: + class ProbeUniformPoints : public vtkm::worklet::WorkletMapPointToCell + { + public: + typedef void ControlSignature(CellSetIn cellset, + FieldInPoint coords, + WholeArrayIn points, + WholeArrayOut cellIds, + WholeArrayOut parametricCoords); + typedef void ExecutionSignature(InputIndex, CellShape, _2, _3, _4, _5); + using InputDomain = _1; + + template + VTKM_EXEC void operator()(vtkm::Id cellId, + CellShapeTag cellShape, + const CoordsVecType& cellPoints, + const UniformPoints& points, + CellIdsType& cellIds, + ParametricCoordsType& pcoords) const + { + // Compute cell bounds + using CoordsType = typename vtkm::VecTraits::ComponentType; + auto numPoints = vtkm::VecTraits::GetNumberOfComponents(cellPoints); + + CoordsType cbmin = cellPoints[0], cbmax = cellPoints[0]; + for (vtkm::IdComponent i = 1; i < numPoints; ++i) + { + cbmin = vtkm::Min(cbmin, cellPoints[i]); + cbmax = vtkm::Max(cbmax, cellPoints[i]); + } + + // Compute points inside cell bounds + auto portal = points.GetPortal(); + auto minp = + static_cast(vtkm::Ceil((cbmin - portal.GetOrigin()) / portal.GetSpacing())); + auto maxp = + static_cast(vtkm::Floor((cbmax - portal.GetOrigin()) / portal.GetSpacing())); + + // clamp + minp = vtkm::Max(minp, vtkm::Id3(0)); + maxp = vtkm::Min(maxp, portal.GetDimensions() - vtkm::Id3(1)); + + for (vtkm::Id k = minp[2]; k <= maxp[2]; ++k) + { + for (vtkm::Id j = minp[1]; j <= maxp[1]; ++j) + { + for (vtkm::Id i = minp[0]; i <= maxp[0]; ++i) + { + auto pt = portal.Get(vtkm::Id3(i, j, k)); + bool success = false; + auto pc = vtkm::exec::WorldCoordinatesToParametricCoordinates( + cellPoints, pt, cellShape, success, *this); + if (success && vtkm::exec::CellInside(pc, cellShape)) + { + auto pointId = i + portal.GetDimensions()[0] * (j + portal.GetDimensions()[1] * k); + cellIds.Set(pointId, cellId); + pcoords.Set(pointId, pc); + } + } + } + } + } + }; + +private: + template + void RunImpl(const CellSetType& cells, + const vtkm::cont::CoordinateSystem& coords, + const vtkm::cont::ArrayHandleUniformPointCoordinates::Superclass& points, + Device) + { + this->InputCellSet = vtkm::cont::DynamicCellSet(cells); + vtkm::cont::DeviceAdapterAlgorithm::Copy( + vtkm::cont::make_ArrayHandleConstant(vtkm::Id(-1), points.GetNumberOfValues()), + this->CellIds); + this->ParametricCoordinates.Allocate(points.GetNumberOfValues()); + + vtkm::worklet::DispatcherMapTopology().Invoke( + cells, coords, points, this->CellIds, this->ParametricCoordinates); + } + + //============================================================================ + struct RunImplCaller + { + template + void operator()(const PointsArrayType& points, + Probe& worklet, + const CellSetType& cells, + const vtkm::cont::CoordinateSystem& coords, + Device device) const + { + worklet.RunImpl(cells, coords, points, device); + } + }; + +public: + template + void Run(const CellSetType& cells, + const vtkm::cont::CoordinateSystem& coords, + const PointsArrayType& points, + Device device) + { + vtkm::cont::CastAndCall(points, RunImplCaller(), *this, cells, coords, device); + } + + //============================================================================ + class InterpolatePointField : public vtkm::worklet::WorkletMapField + { + public: + typedef void ControlSignature(FieldIn cellIds, + FieldIn parametricCoords, + WholeCellSetIn<> inputCells, + WholeArrayIn<> inputField, + FieldOut<> result); + typedef void ExecutionSignature(_1, _2, _3, _4, _5); + + template + VTKM_EXEC void operator()(vtkm::Id cellId, + const ParametricCoordType& pc, + const CellSetType& cells, + const InputFieldPortalType& in, + typename InputFieldPortalType::ValueType& out) const + { + if (cellId != -1) + { + auto indices = cells.GetIndices(cellId); + auto pointVals = vtkm::make_VecFromPortalPermute(&indices, in); + out = vtkm::exec::CellInterpolate(pointVals, pc, cells.GetCellShape(cellId), *this); + } + } + }; + + /// Intepolate the input point field data at the points of the geometry + template + vtkm::cont::ArrayHandle ProcessPointField( + const vtkm::cont::ArrayHandle& field, + Device, + InputCellSetTypeList icsTypes = InputCellSetTypeList()) const + { + vtkm::cont::ArrayHandle result; + vtkm::worklet::DispatcherMapField().Invoke( + this->CellIds, + this->ParametricCoordinates, + this->InputCellSet.ResetCellSetList(icsTypes), + field, + result); + + return result; + } + + //============================================================================ + class MapCellField : public vtkm::worklet::WorkletMapField + { + public: + typedef void ControlSignature(FieldIn cellIds, + WholeArrayIn<> inputField, + FieldOut<> result); + typedef void ExecutionSignature(_1, _2, _3); + + template + VTKM_EXEC void operator()(vtkm::Id cellId, + const InputFieldPortalType& in, + typename InputFieldPortalType::ValueType& out) const + { + if (cellId != -1) + { + out = in.Get(cellId); + } + } + }; + + /// Map the input cell field data to the points of the geometry. Each point gets the value + /// associated with its containing cell. For points that fall on cell edges, the containing + /// cell is chosen arbitrarily. + /// + template + vtkm::cont::ArrayHandle ProcessCellField(const vtkm::cont::ArrayHandle& field, + Device) const + { + vtkm::cont::ArrayHandle result; + vtkm::worklet::DispatcherMapField().Invoke(this->CellIds, field, result); + + return result; + } + + //============================================================================ + struct HiddenPointsWorklet : public WorkletMapField + { + typedef void ControlSignature(FieldIn cellids, + FieldOut> hfield); + typedef _2 ExecutionSignature(_1); + + VTKM_EXEC vtkm::UInt8 operator()(vtkm::Id cellId) const { return (cellId == -1) ? HIDDEN : 0; } + }; + + /// Get an array of flags marking the invalid points (points that do not fall inside any of + /// the cells of the input). The flag value is the same as the HIDDEN flag in VTK and VISIT. + /// + template + vtkm::cont::ArrayHandle GetHiddenPointsField(DeviceAdapter) const + { + vtkm::cont::ArrayHandle field; + vtkm::worklet::DispatcherMapField().Invoke(this->CellIds, + field); + return field; + } + + //============================================================================ + struct HiddenCellsWorklet : public WorkletMapPointToCell + { + typedef void ControlSignature(CellSetIn cellset, + FieldInPoint cellids, + FieldOutCell>); + typedef _3 ExecutionSignature(_2, PointCount); + + template + VTKM_EXEC vtkm::UInt8 operator()(const CellIdsVecType& cellIds, + vtkm::IdComponent numPoints) const + { + for (vtkm::IdComponent i = 0; i < numPoints; ++i) + { + if (cellIds[i] == -1) + { + return HIDDEN; + } + } + return 0; + } + }; + + /// Get an array of flags marking the invalid cells. Invalid cells are the cells with at least + /// one invalid point. The flag value is the same as the HIDDEN flag in VTK and VISIT. + /// + template + vtkm::cont::ArrayHandle GetHiddenCellsField(CellSetType cellset, DeviceAdapter) const + { + vtkm::cont::ArrayHandle field; + vtkm::worklet::DispatcherMapTopology().Invoke( + cellset, this->CellIds, field); + return field; + } + + //============================================================================ +private: + static const vtkm::UInt8 HIDDEN = 2; // from vtk + + vtkm::cont::ArrayHandle CellIds; + vtkm::cont::ArrayHandle> ParametricCoordinates; + vtkm::cont::DynamicCellSet InputCellSet; +}; +} +} // vtkm::worklet + +#endif // vtk_m_worklet_Probe_h diff --git a/vtkm/worklet/RemoveUnusedPoints.h b/vtkm/worklet/RemoveUnusedPoints.h index 4a1918fa7..17cbbac76 100644 --- a/vtkm/worklet/RemoveUnusedPoints.h +++ b/vtkm/worklet/RemoveUnusedPoints.h @@ -202,7 +202,7 @@ public: /// \brief Maps a point field from the original points to the new reduced points /// /// Given an array handle that holds the values for a point field of the - /// orignal data set, returns a new array handle containing field values + /// original data set, returns a new array handle containing field values /// rearranged to the new indices of the reduced point set. /// /// This version of point mapping performs a shallow copy by using a @@ -221,7 +221,7 @@ public: /// \brief Maps a point field from the original points to the new reduced points /// /// Given an array handle that holds the values for a point field of the - /// orignal data set, returns a new array handle containing field values + /// original data set, returns a new array handle containing field values /// rearranged to the new indices of the reduced point set. /// /// This version of point mapping performs a deep copy into the destination @@ -244,7 +244,7 @@ public: /// \brief Maps a point field from the original points to the new reduced points /// /// Given an array handle that holds the values for a point field of the - /// orignal data set, returns a new array handle containing field values + /// original data set, returns a new array handle containing field values /// rearranged to the new indices of the reduced point set. /// /// This version of point mapping performs a deep copy into an array that is diff --git a/vtkm/worklet/ScalarsToColors.h b/vtkm/worklet/ScalarsToColors.h new file mode 100644 index 000000000..3d49c2626 --- /dev/null +++ b/vtkm/worklet/ScalarsToColors.h @@ -0,0 +1,144 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_ScalarsToColors_h +#define vtk_m_worklet_ScalarsToColors_h + +#include +#include + +namespace vtkm +{ +namespace worklet +{ + +namespace colorconversion +{ +inline void ComputeShiftScale(const vtkm::Range& range, vtkm::Float32& shift, vtkm::Float32& scale) +{ + //This scale logic seems to be unduly complicated + shift = static_cast(-range.Min); + scale = static_cast(range.Length()); + + if (range.Length() <= 0) + { + scale = -1e17f; + } + if (scale * scale > 1e-30f) + { + scale = 1.0f / scale; + } + scale *= 255.0f; +} +} + +class ScalarsToColors +{ + vtkm::Range ValueRange = { 0.0f, 255.0f }; + vtkm::Float32 Alpha = 1.0f; + vtkm::Float32 Shift = 0.0f; + vtkm::Float32 Scale = 1.0f; + +public: + ScalarsToColors() {} + + ScalarsToColors(const vtkm::Range& range, vtkm::Float32 alpha) + : ValueRange(range) + , Alpha(vtkm::Min(vtkm::Max(alpha, 0.0f), 1.0f)) + { + colorconversion::ComputeShiftScale(range, this->Shift, this->Scale); + } + + ScalarsToColors(const vtkm::Range& range) + : ValueRange(range) + { + colorconversion::ComputeShiftScale(range, this->Shift, this->Scale); + } + + ScalarsToColors(vtkm::Float32 alpha) + : ValueRange(0.0f, 255.0f) + , Alpha(vtkm::Min(vtkm::Max(alpha, 0.0f), 1.0f)) + { + } + + void SetRange(const vtkm::Range& range) + { + this->ValueRange = range; + colorconversion::ComputeShiftScale(range, this->Shift, this->Scale); + } + + vtkm::Range GetRange() const { return this->ValueRange; } + + void SetAlpha(vtkm::Float32 alpha) { this->Alpha = vtkm::Min(vtkm::Max(alpha, 0.0f), 1.0f); } + + vtkm::Float32 GetAlpha() const { return this->Alpha; } + + /// \brief Use each component to generate RGBA colors + /// + template + void Run(const vtkm::cont::ArrayHandle& values, + vtkm::cont::ArrayHandle>& rgbaOut, + Device) const; + + /// \brief Use each component to generate RGB colors + /// + template + void Run(const vtkm::cont::ArrayHandle& values, + vtkm::cont::ArrayHandle>& rgbOut, + Device) const; + + + /// \brief Use magnitude of a vector to generate RGBA colors + /// + template + void RunMagnitude(const vtkm::cont::ArrayHandle, S>& values, + vtkm::cont::ArrayHandle>& rgbaOut, + Device) const; + + /// \brief Use magnitude of a vector to generate RGB colors + /// + template + void RunMagnitude(const vtkm::cont::ArrayHandle, S>& values, + vtkm::cont::ArrayHandle>& rgbOut, + Device) const; + + /// \brief Use a single component of a vector to generate RGBA colors + /// + template + void RunComponent(const vtkm::cont::ArrayHandle, S>& values, + vtkm::IdComponent comp, + vtkm::cont::ArrayHandle>& rgbaOut, + Device) const; + + /// \brief Use a single component of a vector to generate RGB colors + /// + template + void RunComponent(const vtkm::cont::ArrayHandle, S>& values, + vtkm::IdComponent comp, + vtkm::cont::ArrayHandle>& rgbOut, + Device) const; +}; +} +} + +#include + +#endif diff --git a/vtkm/worklet/ScalarsToColors.hxx b/vtkm/worklet/ScalarsToColors.hxx new file mode 100644 index 000000000..9c5a083ab --- /dev/null +++ b/vtkm/worklet/ScalarsToColors.hxx @@ -0,0 +1,188 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ +inline bool needShiftScale(vtkm::Float32, vtkm::Float32 shift, vtkm::Float32 scale) +{ + return !((shift == -0.0f || shift == 0.0f) && (scale == 255.0f)); +} +inline bool needShiftScale(vtkm::Float64, vtkm::Float32 shift, vtkm::Float32 scale) +{ + return !((shift == -0.0f || shift == 0.0f) && (scale == 255.0f)); +} +inline bool needShiftScale(vtkm::UInt8, vtkm::Float32 shift, vtkm::Float32 scale) +{ + return !((shift == -0.0f || shift == 0.0f) && (scale == 1.0f)); +} + +template +inline bool needShiftScale(T, vtkm::Float32, vtkm::Float32) +{ + return true; +} +} +/// \brief Use each component to generate RGBA colors +/// +template +void ScalarsToColors::Run(const vtkm::cont::ArrayHandle& values, + vtkm::cont::ArrayHandle>& rgbaOut, + Device) const +{ + using namespace vtkm::worklet::colorconversion; + //If our shift is 0 and our scale == 1 no need to apply them + using BaseT = typename vtkm::BaseComponent::Type; + const bool shiftscale = needShiftScale(BaseT{}, this->Shift, this->Scale); + if (shiftscale) + { + vtkm::worklet::DispatcherMapField dispatcher( + ShiftScaleToRGBA(this->Shift, this->Scale, this->Alpha)); + dispatcher.Invoke(values, rgbaOut); + } + else + { + vtkm::worklet::DispatcherMapField dispatcher(ConvertToRGBA(this->Alpha)); + dispatcher.Invoke(values, rgbaOut); + } +} + +/// \brief Use each component to generate RGB colors +/// +template +void ScalarsToColors::Run(const vtkm::cont::ArrayHandle& values, + vtkm::cont::ArrayHandle>& rgbOut, + Device) const +{ + using namespace vtkm::worklet::colorconversion; + using BaseT = typename vtkm::BaseComponent::Type; + const bool shiftscale = needShiftScale(BaseT{}, this->Shift, this->Scale); + if (shiftscale) + { + vtkm::worklet::DispatcherMapField dispatcher( + ShiftScaleToRGB(this->Shift, this->Scale)); + dispatcher.Invoke(values, rgbOut); + } + else + { + vtkm::worklet::DispatcherMapField dispatcher; + dispatcher.Invoke(values, rgbOut); + } +} + +/// \brief Use magnitude of a vector to generate RGBA colors +/// +template +void ScalarsToColors::RunMagnitude(const vtkm::cont::ArrayHandle, S>& values, + vtkm::cont::ArrayHandle>& rgbaOut, + Device) const +{ + //magnitude is a complex situation. the default scale factor is incorrect + // + using namespace vtkm::worklet::colorconversion; + //If our shift is 0 and our scale == 1 no need to apply them + using BaseT = typename vtkm::BaseComponent::Type; + const bool shiftscale = needShiftScale(BaseT{}, this->Shift, this->Scale); + if (shiftscale) + { + vtkm::worklet::DispatcherMapField dispatcher( + ShiftScaleToRGBA(this->Shift, this->Scale, this->Alpha)); + dispatcher.Invoke( + vtkm::cont::make_ArrayHandleTransform(values, colorconversion::MagnitudePortal()), rgbaOut); + } + else + { + vtkm::worklet::DispatcherMapField dispatcher(ConvertToRGBA(this->Alpha)); + dispatcher.Invoke( + vtkm::cont::make_ArrayHandleTransform(values, colorconversion::MagnitudePortal()), rgbaOut); + } +} + +/// \brief Use magnitude of a vector to generate RGB colors +/// +template +void ScalarsToColors::RunMagnitude(const vtkm::cont::ArrayHandle, S>& values, + vtkm::cont::ArrayHandle>& rgbOut, + Device) const +{ + + using namespace vtkm::worklet::colorconversion; + using BaseT = typename vtkm::BaseComponent::Type; + const bool shiftscale = needShiftScale(BaseT{}, this->Shift, this->Scale); + if (shiftscale) + { + vtkm::worklet::DispatcherMapField dispatcher( + ShiftScaleToRGB(this->Shift, this->Scale)); + dispatcher.Invoke( + vtkm::cont::make_ArrayHandleTransform(values, colorconversion::MagnitudePortal()), rgbOut); + } + else + { + vtkm::worklet::DispatcherMapField dispatcher; + dispatcher.Invoke( + vtkm::cont::make_ArrayHandleTransform(values, colorconversion::MagnitudePortal()), rgbOut); + } +} + +/// \brief Use a single component of a vector to generate RGBA colors +/// +template +void ScalarsToColors::RunComponent(const vtkm::cont::ArrayHandle, S>& values, + vtkm::IdComponent comp, + vtkm::cont::ArrayHandle>& rgbaOut, + Device device) const +{ + this->Run(vtkm::cont::make_ArrayHandleTransform(values, colorconversion::ComponentPortal(comp)), + rgbaOut, + device); +} + +/// \brief Use a single component of a vector to generate RGB colors +/// +template +void ScalarsToColors::RunComponent(const vtkm::cont::ArrayHandle, S>& values, + vtkm::IdComponent comp, + vtkm::cont::ArrayHandle>& rgbOut, + Device device) const +{ + this->Run(vtkm::cont::make_ArrayHandleTransform(values, colorconversion::ComponentPortal(comp)), + rgbOut, + device); +} +} +} diff --git a/vtkm/worklet/ScatterCounting.h b/vtkm/worklet/ScatterCounting.h index c1f2a8887..07036c368 100644 --- a/vtkm/worklet/ScatterCounting.h +++ b/vtkm/worklet/ScatterCounting.h @@ -185,7 +185,7 @@ struct ScatterCounting { } - typedef vtkm::cont::ArrayHandle OutputToInputMapType; + using OutputToInputMapType = vtkm::cont::ArrayHandle; template VTKM_CONT OutputToInputMapType GetOutputToInputMap(RangeType) const @@ -193,7 +193,7 @@ struct ScatterCounting return this->OutputToInputMap; } - typedef vtkm::cont::ArrayHandle VisitArrayType; + using VisitArrayType = vtkm::cont::ArrayHandle; template VTKM_CONT VisitArrayType GetVisitArray(RangeType) const { diff --git a/vtkm/worklet/ScatterIdentity.h b/vtkm/worklet/ScatterIdentity.h index 110d48a27..431ff095e 100644 --- a/vtkm/worklet/ScatterIdentity.h +++ b/vtkm/worklet/ScatterIdentity.h @@ -40,7 +40,7 @@ namespace worklet /// struct ScatterIdentity { - typedef vtkm::cont::ArrayHandleIndex OutputToInputMapType; + using OutputToInputMapType = vtkm::cont::ArrayHandleIndex; VTKM_CONT OutputToInputMapType GetOutputToInputMap(vtkm::Id inputRange) const { @@ -52,7 +52,7 @@ struct ScatterIdentity return this->GetOutputToInputMap(inputRange[0] * inputRange[1] * inputRange[2]); } - typedef vtkm::cont::ArrayHandleConstant VisitArrayType; + using VisitArrayType = vtkm::cont::ArrayHandleConstant; VTKM_CONT VisitArrayType GetVisitArray(vtkm::Id inputRange) const { return VisitArrayType(0, inputRange); } VTKM_CONT diff --git a/vtkm/worklet/ScatterUniform.h b/vtkm/worklet/ScatterUniform.h index 422ad4dff..2ae7c80f3 100644 --- a/vtkm/worklet/ScatterUniform.h +++ b/vtkm/worklet/ScatterUniform.h @@ -93,7 +93,7 @@ struct ScatterUniform return this->GetOutputRange(inputRange[0] * inputRange[1] * inputRange[2]); } - typedef vtkm::cont::ArrayHandleImplicit OutputToInputMapType; + using OutputToInputMapType = vtkm::cont::ArrayHandleImplicit; template VTKM_CONT OutputToInputMapType GetOutputToInputMap(RangeType inputRange) const { @@ -101,7 +101,7 @@ struct ScatterUniform this->GetOutputRange(inputRange)); } - typedef vtkm::cont::ArrayHandleImplicit VisitArrayType; + using VisitArrayType = vtkm::cont::ArrayHandleImplicit; template VTKM_CONT VisitArrayType GetVisitArray(RangeType inputRange) const { diff --git a/vtkm/worklet/StreamLineUniformGrid.h b/vtkm/worklet/StreamLineUniformGrid.h index 17f75eff4..253115e28 100644 --- a/vtkm/worklet/StreamLineUniformGrid.h +++ b/vtkm/worklet/StreamLineUniformGrid.h @@ -155,9 +155,9 @@ public: } }; - typedef vtkm::cont::ArrayHandle> FieldHandle; - typedef - typename FieldHandle::template ExecutionTypes::PortalConst FieldPortalConstType; + using FieldHandle = vtkm::cont::ArrayHandle>; + using FieldPortalConstType = + typename FieldHandle::template ExecutionTypes::PortalConst; class MakeStreamLines : public vtkm::worklet::WorkletMapField { @@ -168,9 +168,9 @@ public: WholeArrayOut validPoint, WholeArrayOut streamLines); typedef void ExecutionSignature(_1, _2, _3, _4, _5, VisitIndex); - typedef _1 InputDomain; + using InputDomain = _1; - typedef vtkm::worklet::ScatterUniform ScatterType; + using ScatterType = vtkm::worklet::ScatterUniform; VTKM_CONT ScatterType GetScatter() const { return ScatterType(2); } @@ -346,7 +346,7 @@ public: vtkm::Id maxSteps, FieldType timeStep) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // Get information from input dataset vtkm::cont::CellSetStructured<3> inCellSet; @@ -398,7 +398,7 @@ public: // Worklet to make the streamlines MakeStreamLines makeStreamLines( timeStep, streamMode, maxSteps, vdims, fieldArray.PrepareForInput(DeviceAdapter())); - typedef typename vtkm::worklet::DispatcherMapField MakeStreamLinesDispatcher; + using MakeStreamLinesDispatcher = typename vtkm::worklet::DispatcherMapField; MakeStreamLinesDispatcher makeStreamLinesDispatcher(makeStreamLines); makeStreamLinesDispatcher.Invoke( seedIdArray, seedPosArray, numIndices, validPoint, streamArray); diff --git a/vtkm/worklet/Tetrahedralize.h b/vtkm/worklet/Tetrahedralize.h index a89ed8266..0f2759417 100644 --- a/vtkm/worklet/Tetrahedralize.h +++ b/vtkm/worklet/Tetrahedralize.h @@ -39,7 +39,7 @@ public: typedef void ControlSignature(FieldIn<> inIndices, FieldOut<> outIndices); typedef void ExecutionSignature(_1, _2); - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } diff --git a/vtkm/worklet/Threshold.h b/vtkm/worklet/Threshold.h index 736daadac..8c7d6a8d2 100644 --- a/vtkm/worklet/Threshold.h +++ b/vtkm/worklet/Threshold.h @@ -138,7 +138,7 @@ public: { case vtkm::cont::Field::ASSOC_POINTS: { - typedef ThresholdByPointField ThresholdWorklet; + using ThresholdWorklet = ThresholdByPointField; ThresholdWorklet worklet(predicate); DispatcherMapTopology dispatcher(worklet); @@ -147,7 +147,7 @@ public: } case vtkm::cont::Field::ASSOC_CELL_SET: { - typedef ThresholdByCellField ThresholdWorklet; + using ThresholdWorklet = ThresholdByCellField; ThresholdWorklet worklet(predicate); DispatcherMapTopology dispatcher(worklet); diff --git a/vtkm/worklet/ThresholdPoints.h b/vtkm/worklet/ThresholdPoints.h index bf67cb784..c368b274b 100644 --- a/vtkm/worklet/ThresholdPoints.h +++ b/vtkm/worklet/ThresholdPoints.h @@ -79,11 +79,11 @@ public: const UnaryPredicate& predicate, DeviceAdapter) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle passFlags; - typedef ThresholdPointField ThresholdWorklet; + using ThresholdWorklet = ThresholdPointField; ThresholdWorklet worklet(predicate); DispatcherMapTopology dispatcher(worklet); diff --git a/vtkm/worklet/Triangulate.h b/vtkm/worklet/Triangulate.h index 08de547af..0cceaf3c5 100644 --- a/vtkm/worklet/Triangulate.h +++ b/vtkm/worklet/Triangulate.h @@ -39,7 +39,7 @@ public: typedef void ControlSignature(FieldIn<> inIndices, FieldOut<> outIndices); typedef void ExecutionSignature(_1, _2); - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } diff --git a/vtkm/worklet/VertexClustering.h b/vtkm/worklet/VertexClustering.h index ac23b75d2..209dec5b1 100644 --- a/vtkm/worklet/VertexClustering.h +++ b/vtkm/worklet/VertexClustering.h @@ -167,7 +167,7 @@ struct VertexClustering template VTKM_EXEC vtkm::Id GetClusterId(const PointType& p) const { - typedef typename PointType::ComponentType ComponentType; + using ComponentType = typename PointType::ComponentType; PointType gridOrigin(static_cast(this->Grid.origin[0]), static_cast(this->Grid.origin[1]), static_cast(this->Grid.origin[2])); diff --git a/vtkm/worklet/WaveletCompressor.h b/vtkm/worklet/WaveletCompressor.h index 5f5dbebe9..b4b97749a 100644 --- a/vtkm/worklet/WaveletCompressor.h +++ b/vtkm/worklet/WaveletCompressor.h @@ -70,12 +70,12 @@ public: std::vector L1d(3, 0); // Use an intermediate array - typedef typename CoeffArrayType::ValueType OutputValueType; - typedef vtkm::cont::ArrayHandle InterArrayType; + using OutputValueType = typename CoeffArrayType::ValueType; + using InterArrayType = vtkm::cont::ArrayHandle; // Define a few more types - typedef vtkm::cont::ArrayHandleCounting IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermutArrayType; + using IdArrayType = vtkm::cont::ArrayHandleCounting; + using PermutArrayType = vtkm::cont::ArrayHandlePermutation; vtkm::cont::ArrayCopy(sigIn, coeffOut, DeviceTag()); @@ -120,10 +120,10 @@ public: L1d[0] = L[0]; L1d[1] = L[1]; - typedef typename SignalArrayType::ValueType OutValueType; - typedef vtkm::cont::ArrayHandle OutArrayBasic; - typedef vtkm::cont::ArrayHandleCounting IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermutArrayType; + using OutValueType = typename SignalArrayType::ValueType; + using OutArrayBasic = vtkm::cont::ArrayHandle; + using IdArrayType = vtkm::cont::ArrayHandleCounting; + using PermutArrayType = vtkm::cont::ArrayHandlePermutation; vtkm::cont::ArrayCopy(coeffIn, sigOut, DeviceTag()); @@ -181,8 +181,8 @@ public: vtkm::Id currentLenZ = inZ; std::vector L3d(27, 0); - typedef typename OutArrayType::ValueType OutValueType; - typedef vtkm::cont::ArrayHandle OutBasicArray; + using OutValueType = typename OutArrayType::ValueType; + using OutBasicArray = vtkm::cont::ArrayHandle; // First level transform writes to the output array vtkm::Float64 computationTime = WaveletDWT::DWT3D(sigIn, @@ -260,8 +260,8 @@ public: { throw vtkm::cont::ErrorBadValue("Number of levels of transform is not supported! "); } - typedef typename OutArrayType::ValueType OutValueType; - typedef vtkm::cont::ArrayHandle OutBasicArray; + using OutValueType = typename OutArrayType::ValueType; + using OutBasicArray = vtkm::cont::ArrayHandle; vtkm::Float64 computationTime = 0.0; OutBasicArray outBuffer; @@ -356,8 +356,8 @@ public: std::vector L2d(10, 0); vtkm::Float64 computationTime = 0.0; - typedef typename OutArrayType::ValueType OutValueType; - typedef vtkm::cont::ArrayHandle OutBasicArray; + using OutValueType = typename OutArrayType::ValueType; + using OutBasicArray = vtkm::cont::ArrayHandle; // First level transform operates writes to the output array computationTime += WaveletDWT::DWT2D( @@ -403,8 +403,8 @@ public: { throw vtkm::cont::ErrorBadValue("Number of levels of transform is not supported! "); } - typedef typename OutArrayType::ValueType OutValueType; - typedef vtkm::cont::ArrayHandle OutBasicArray; + using OutValueType = typename OutArrayType::ValueType; + using OutBasicArray = vtkm::cont::ArrayHandle; vtkm::Float64 computationTime = 0.0; OutBasicArray outBuffer; @@ -472,8 +472,8 @@ public: if (ratio > 1.0) { vtkm::Id coeffLen = coeffIn.GetNumberOfValues(); - typedef typename CoeffArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle CoeffArrayBasic; + using ValueType = typename CoeffArrayType::ValueType; + using CoeffArrayBasic = vtkm::cont::ArrayHandle; CoeffArrayBasic sortedArray; vtkm::cont::ArrayCopy(coeffIn, sortedArray, DeviceTag()); @@ -486,7 +486,7 @@ public: nthVal *= -1.0; } - typedef vtkm::worklet::wavelets::ThresholdWorklet ThresholdType; + using ThresholdType = vtkm::worklet::wavelets::ThresholdWorklet; ThresholdType thresholdWorklet(nthVal); vtkm::worklet::DispatcherMapField dispatcher(thresholdWorklet); dispatcher.Invoke(coeffIn); @@ -505,17 +505,17 @@ public: #define MAKEVAL(a) (static_cast(a)) VAL VarOrig = WaveletBase::DeviceCalculateVariance(original, DeviceTag()); - typedef typename ArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ArrayBasic; + using ValueType = typename ArrayType::ValueType; + using ArrayBasic = vtkm::cont::ArrayHandle; ArrayBasic errorArray, errorSquare; // Use a worklet to calculate point-wise error, and its square - typedef vtkm::worklet::wavelets::Differencer DifferencerWorklet; + using DifferencerWorklet = vtkm::worklet::wavelets::Differencer; DifferencerWorklet dw; vtkm::worklet::DispatcherMapField dwDispatcher(dw); dwDispatcher.Invoke(original, reconstruct, errorArray); - typedef vtkm::worklet::wavelets::SquareWorklet SquareWorklet; + using SquareWorklet = vtkm::worklet::wavelets::SquareWorklet; SquareWorklet sw; vtkm::worklet::DispatcherMapField swDispatcher(sw); swDispatcher.Invoke(errorArray, errorSquare); diff --git a/vtkm/worklet/WorkletMapField.h b/vtkm/worklet/WorkletMapField.h index 18e84e802..13c4c526f 100644 --- a/vtkm/worklet/WorkletMapField.h +++ b/vtkm/worklet/WorkletMapField.h @@ -54,9 +54,9 @@ public: template struct FieldIn : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagArrayIn TransportTag; - typedef vtkm::exec::arg::FetchTagArrayDirectIn FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagArrayIn; + using FetchTag = vtkm::exec::arg::FetchTagArrayDirectIn; }; /// \brief A control signature tag for output fields. @@ -67,9 +67,9 @@ public: template struct FieldOut : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagArrayOut TransportTag; - typedef vtkm::exec::arg::FetchTagArrayDirectOut FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagArrayOut; + using FetchTag = vtkm::exec::arg::FetchTagArrayDirectOut; }; /// \brief A control signature tag for input-output (in-place) fields. @@ -80,9 +80,9 @@ public: template struct FieldInOut : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagArrayInOut TransportTag; - typedef vtkm::exec::arg::FetchTagArrayDirectInOut FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagArrayInOut; + using FetchTag = vtkm::exec::arg::FetchTagArrayDirectInOut; }; }; } diff --git a/vtkm/worklet/WorkletPointNeighborhood.h b/vtkm/worklet/WorkletPointNeighborhood.h index 70cf326e6..b82ebdbcb 100644 --- a/vtkm/worklet/WorkletPointNeighborhood.h +++ b/vtkm/worklet/WorkletPointNeighborhood.h @@ -94,7 +94,7 @@ public: }; /// All worklets must define their scatter operation. - typedef vtkm::worklet::ScatterIdentity ScatterType; + using ScatterType = vtkm::worklet::ScatterIdentity; /// In addition to defining the scatter type, the worklet must produce the /// scatter. The default vtkm::worklet::ScatterIdentity has no state, @@ -104,7 +104,7 @@ public: /// All neighborhood worklets must define their boundary type operation. /// The boundary type determines how loading on boundaries will work. - typedef vtkm::worklet::BoundaryClamp BoundaryType; + using BoundaryType = vtkm::worklet::BoundaryClamp; /// In addition to defining the boundary type, the worklet must produce the /// boundary condition. The default BoundaryClamp has no state, so just return an diff --git a/vtkm/worklet/colorconversion/CMakeLists.txt b/vtkm/worklet/colorconversion/CMakeLists.txt new file mode 100644 index 000000000..f49151446 --- /dev/null +++ b/vtkm/worklet/colorconversion/CMakeLists.txt @@ -0,0 +1,31 @@ +##============================================================================ +## Copyright (c) Kitware, Inc. +## All rights reserved. +## See LICENSE.txt for details. +## This software is distributed WITHOUT ANY WARRANTY; without even +## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +## PURPOSE. See the above copyright notice for more information. +## +## Copyright 2016 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +## Copyright 2016 UT-Battelle, LLC. +## Copyright 2016 Los Alamos National Security. +## +## Under the terms of Contract DE-NA0003525 with NTESS, +## the U.S. Government retains certain rights in this software. +## +## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +## Laboratory (LANL), the U.S. Government retains certain rights in +## this software. +##============================================================================ + +set(headers + Conversions.h + ConvertToRGB.h + ConvertToRGBA.h + Portals.h + ShiftScaleToRGB.h + ShiftScaleToRGBA.h + ) + +#----------------------------------------------------------------------------- +vtkm_declare_headers(${headers}) diff --git a/vtkm/worklet/colorconversion/Conversions.h b/vtkm/worklet/colorconversion/Conversions.h new file mode 100644 index 000000000..1475a3520 --- /dev/null +++ b/vtkm/worklet/colorconversion/Conversions.h @@ -0,0 +1,76 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_Conversions_h +#define vtk_m_worklet_colorconversion_Conversions_h + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +template +VTKM_EXEC inline vtkm::UInt8 ColorToUChar(T t) +{ + return static_cast(t); +} + +template <> +VTKM_EXEC inline vtkm::UInt8 ColorToUChar(vtkm::Float64 t) +{ + return static_cast(t * 255.0f + 0.5f); +} + +template <> +VTKM_EXEC inline vtkm::UInt8 ColorToUChar(vtkm::Float32 t) +{ + return static_cast(t * 255.0f + 0.5f); +} + + +VTKM_EXEC inline void Clamp(vtkm::Float32& val) +{ + val = vtkm::Min(255.0f, vtkm::Max(0.0f, val)); +} +VTKM_EXEC inline void Clamp(vtkm::Vec& val) +{ + val[0] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[0])); + val[1] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[1])); +} +VTKM_EXEC inline void Clamp(vtkm::Vec& val) +{ + val[0] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[0])); + val[1] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[1])); + val[2] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[2])); +} +VTKM_EXEC inline void Clamp(vtkm::Vec& val) +{ + val[0] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[0])); + val[1] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[1])); + val[2] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[2])); + val[3] = vtkm::Min(255.0f, vtkm::Max(0.0f, val[3])); +} +} +} +} +#endif diff --git a/vtkm/worklet/colorconversion/ConvertToRGB.h b/vtkm/worklet/colorconversion/ConvertToRGB.h new file mode 100644 index 000000000..52f7bdde6 --- /dev/null +++ b/vtkm/worklet/colorconversion/ConvertToRGB.h @@ -0,0 +1,76 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_ConvertToRGB_h +#define vtk_m_worklet_colorconversion_ConvertToRGB_h + +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +struct ConvertToRGB : public vtkm::worklet::WorkletMapField +{ + typedef void ControlSignature(FieldIn<> in, FieldOut<> out); + typedef _2 ExecutionSignature(_1); + + template + VTKM_EXEC vtkm::Vec operator()(const T& in) const + { //vtkScalarsToColorsLuminanceToRGB + const vtkm::UInt8 la = colorconversion::ColorToUChar(in); + return vtkm::Vec(la, la, la); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsLuminanceAlphaToRGB (which actually doesn't exist in vtk) + return this->operator()(in[0]); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBToRGB + return vtkm::Vec(colorconversion::ColorToUChar(in[0]), + colorconversion::ColorToUChar(in[1]), + colorconversion::ColorToUChar(in[2])); + } + + vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBToRGB + return in; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBAToRGB + return vtkm::Vec(colorconversion::ColorToUChar(in[0]), + colorconversion::ColorToUChar(in[1]), + colorconversion::ColorToUChar(in[2])); + } +}; +} +} +} +#endif diff --git a/vtkm/worklet/colorconversion/ConvertToRGBA.h b/vtkm/worklet/colorconversion/ConvertToRGBA.h new file mode 100644 index 000000000..0c89f7183 --- /dev/null +++ b/vtkm/worklet/colorconversion/ConvertToRGBA.h @@ -0,0 +1,83 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_ScalarsToColors_h +#define vtk_m_worklet_colorconversion_ScalarsToColors_h + +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +struct ConvertToRGBA : public vtkm::worklet::WorkletMapField +{ + typedef void ControlSignature(FieldIn<> in, FieldOut<> out); + typedef _2 ExecutionSignature(_1); + + ConvertToRGBA(vtkm::Float32 alpha) + : Alpha(alpha) + { + } + + template + VTKM_EXEC vtkm::Vec operator()(const T& in) const + { //vtkScalarsToColorsLuminanceToRGBA + const vtkm::UInt8 l = colorconversion::ColorToUChar(in); + return vtkm::Vec(l, l, l, colorconversion::ColorToUChar(this->Alpha)); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsLuminanceAlphaToRGBA + const vtkm::UInt8 l = colorconversion::ColorToUChar(in[0]); + const vtkm::UInt8 a = colorconversion::ColorToUChar(in[1]); + return vtkm::Vec(l, l, l, static_cast(a * this->Alpha + 0.5f)); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBToRGBA + return vtkm::Vec(colorconversion::ColorToUChar(in[0]), + colorconversion::ColorToUChar(in[1]), + colorconversion::ColorToUChar(in[2]), + colorconversion::ColorToUChar(this->Alpha)); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBAToRGBA + const vtkm::UInt8 a = colorconversion::ColorToUChar(in[3]); + return vtkm::Vec(colorconversion::ColorToUChar(in[0]), + colorconversion::ColorToUChar(in[1]), + colorconversion::ColorToUChar(in[2]), + static_cast(a * this->Alpha + 0.5f)); + } + + const vtkm::Float32 Alpha = 1.0f; +}; +} +} +} +#endif diff --git a/vtkm/worklet/colorconversion/Portals.h b/vtkm/worklet/colorconversion/Portals.h new file mode 100644 index 000000000..5bb372ee0 --- /dev/null +++ b/vtkm/worklet/colorconversion/Portals.h @@ -0,0 +1,68 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_Portals_h +#define vtk_m_worklet_colorconversion_Portals_h + +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +struct MagnitudePortal +{ + template + VTKM_EXEC auto operator()(const vtkm::Vec& values) const + -> decltype(vtkm::Magnitude(values)) + { //Should we be using RMag? + return vtkm::Magnitude(values); + } +}; + +struct ComponentPortal +{ + vtkm::IdComponent Component; + + ComponentPortal() + : Component(0) + { + } + + ComponentPortal(vtkm::IdComponent comp) + : Component(comp) + { + } + + template + VTKM_EXEC auto operator()(T&& value) const -> + typename std::remove_reference::type + { + return value[this->Component]; + } +}; +} +} +} +#endif diff --git a/vtkm/worklet/colorconversion/ShiftScaleToRGB.h b/vtkm/worklet/colorconversion/ShiftScaleToRGB.h new file mode 100644 index 000000000..f30ca7b5b --- /dev/null +++ b/vtkm/worklet/colorconversion/ShiftScaleToRGB.h @@ -0,0 +1,85 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_ShiftScaleToRGB_h +#define vtk_m_worklet_colorconversion_ShiftScaleToRGB_h + +#include + +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +struct ShiftScaleToRGB : public vtkm::worklet::WorkletMapField +{ + typedef void ControlSignature(FieldIn<> in, FieldOut<> out); + typedef _2 ExecutionSignature(_1); + + ShiftScaleToRGB(vtkm::Float32 shift, vtkm::Float32 scale) + : Shift(shift) + , Scale(scale) + { + } + + template + VTKM_EXEC vtkm::Vec operator()(const T& in) const + { //vtkScalarsToColorsLuminanceToRGB + vtkm::Float32 l = (static_cast(in) + this->Shift) * this->Scale; + colorconversion::Clamp(l); + return vtkm::Vec{ static_cast(l + 0.5f) }; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsLuminanceAlphaToRGB (which actually doesn't exist in vtk) + return this->operator()(in[0]); + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBToRGB + vtkm::Vec rgb(in); + rgb = (rgb + vtkm::Vec(this->Shift)) * this->Scale; + colorconversion::Clamp(rgb); + return vtkm::Vec{ static_cast(rgb[0] + 0.5f), + static_cast(rgb[1] + 0.5f), + static_cast(rgb[2] + 0.5f) }; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBAToRGB + return this->operator()(vtkm::Vec{ in[0], in[1], in[2] }); + } + +private: + const vtkm::Float32 Shift; + const vtkm::Float32 Scale; +}; +} +} +} +#endif diff --git a/vtkm/worklet/colorconversion/ShiftScaleToRGBA.h b/vtkm/worklet/colorconversion/ShiftScaleToRGBA.h new file mode 100644 index 000000000..7df1fc552 --- /dev/null +++ b/vtkm/worklet/colorconversion/ShiftScaleToRGBA.h @@ -0,0 +1,105 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2015 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2015 UT-Battelle, LLC. +// Copyright 2015 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_colorconversion_ShiftScaleToRGBA_h +#define vtk_m_worklet_colorconversion_ShiftScaleToRGBA_h + +#include +#include + +#include + +namespace vtkm +{ +namespace worklet +{ +namespace colorconversion +{ + +struct ShiftScaleToRGBA : public vtkm::worklet::WorkletMapField +{ + const vtkm::Float32 Shift; + const vtkm::Float32 Scale; + const vtkm::Float32 Alpha; + + typedef void ControlSignature(FieldIn<> in, FieldOut<> out); + typedef _2 ExecutionSignature(_1); + + ShiftScaleToRGBA(vtkm::Float32 shift, vtkm::Float32 scale, vtkm::Float32 alpha) + : WorkletMapField() + , Shift(shift) + , Scale(scale) + , Alpha(alpha) + { + } + + template + VTKM_EXEC vtkm::Vec operator()(const T& in) const + { //vtkScalarsToColorsLuminanceToRGBA + vtkm::Float32 l = (static_cast(in) + this->Shift) * this->Scale; + colorconversion::Clamp(l); + const vtkm::UInt8 lc = static_cast(l + 0.5); + return vtkm::Vec{ lc, lc, lc, colorconversion::ColorToUChar(this->Alpha) }; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsLuminanceAlphaToRGBA + vtkm::Vec la(in); + la = (la + vtkm::Vec(this->Shift)) * this->Scale; + colorconversion::Clamp(la); + + const vtkm::UInt8 lc = static_cast(la[0] + 0.5f); + return vtkm::Vec{ + lc, lc, lc, static_cast((la[1] * this->Alpha) + 0.5f) + }; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBToRGBA + vtkm::Vec rgb(in); + rgb = (rgb + vtkm::Vec(this->Shift)) * this->Scale; + colorconversion::Clamp(rgb); + return vtkm::Vec{ static_cast(rgb[0] + 0.5f), + static_cast(rgb[1] + 0.5f), + static_cast(rgb[2] + 0.5f), + colorconversion::ColorToUChar(this->Alpha) }; + } + + template + VTKM_EXEC vtkm::Vec operator()(const vtkm::Vec& in) const + { //vtkScalarsToColorsRGBAToRGBA + vtkm::Vec rgba(in); + rgba = (rgba + vtkm::Vec(this->Shift)) * this->Scale; + colorconversion::Clamp(rgba); + + rgba[3] *= this->Alpha; + return vtkm::Vec{ static_cast(rgba[0] + 0.5f), + static_cast(rgba[1] + 0.5f), + static_cast(rgba[2] + 0.5f), + static_cast(rgba[3] + 0.5f) }; + } +}; +} +} +} +#endif diff --git a/vtkm/worklet/connectivities/CMakeLists.txt b/vtkm/worklet/connectivities/CMakeLists.txt new file mode 100644 index 000000000..3bea891e1 --- /dev/null +++ b/vtkm/worklet/connectivities/CMakeLists.txt @@ -0,0 +1,29 @@ +##============================================================================ +## Copyright (c) Kitware, Inc. +## All rights reserved. +## See LICENSE.txt for details. +## This software is distributed WITHOUT ANY WARRANTY; without even +## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +## PURPOSE. See the above copyright notice for more information. +## +## Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +## Copyright 2018 UT-Battelle, LLC. +## Copyright 2018 Los Alamos National Security. +## +## Under the terms of Contract DE-NA0003525 with NTESS, +## the U.S. Government retains certain rights in this software. +## +## Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +## Laboratory (LANL), the U.S. Government retains certain rights in +## this software. +##============================================================================ + +set(headers + CellSetConnectivity.h + CellSetDualGraph.h + GraphConnectivity.h + InnerJoin.h + ) + +#----------------------------------------------------------------------------- +vtkm_declare_headers(${headers}) diff --git a/vtkm/worklet/connectivities/CellSetConnectivity.h b/vtkm/worklet/connectivities/CellSetConnectivity.h new file mode 100644 index 000000000..ed09feb3e --- /dev/null +++ b/vtkm/worklet/connectivities/CellSetConnectivity.h @@ -0,0 +1,48 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_connectivity_CellSetConnectivity_h +#define vtk_m_worklet_connectivity_CellSetConnectivity_h + +#include +#include + +class CellSetConnectivity +{ +public: + template + void Run(const CellSetType& cellSet, + vtkm::cont::ArrayHandle& componentArray, + DeviceAdapter) const + { + vtkm::cont::ArrayHandle numIndicesArray; + vtkm::cont::ArrayHandle indexOffsetArray; + vtkm::cont::ArrayHandle connectivityArray; + + // create cell to cell connectivity graph (dual graph) + CellSetDualGraph().Run( + cellSet, numIndicesArray, indexOffsetArray, connectivityArray); + // find the connected component of the dual graph + GraphConnectivity().Run( + numIndicesArray, indexOffsetArray, connectivityArray, componentArray); + } +}; +#endif // vtk_m_worklet_connectivity_CellSetConnectivity_h diff --git a/vtkm/worklet/connectivities/CellSetDualGraph.h b/vtkm/worklet/connectivities/CellSetDualGraph.h new file mode 100644 index 000000000..6a74a12ae --- /dev/null +++ b/vtkm/worklet/connectivities/CellSetDualGraph.h @@ -0,0 +1,186 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#ifndef vtk_m_worklet_CellSetDualGraph_h +#define vtk_m_worklet_CellSetDualGraph_h + +#include +#include +#include +#include +#include + +struct EdgeCount : public vtkm::worklet::WorkletMapPointToCell +{ + typedef void ControlSignature(CellSetIn, FieldOutCell<> numEdgesInCell); + typedef _2 ExecutionSignature(CellShape, PointCount); + using InputDomain = _1; + + template + VTKM_EXEC vtkm::IdComponent operator()(CellShapeTag cellShape, vtkm::IdComponent pointCount) const + { + return vtkm::exec::CellEdgeNumberOfEdges(pointCount, cellShape, *this); + } +}; + +struct EdgeExtract : public vtkm::worklet::WorkletMapPointToCell +{ + typedef void ControlSignature(CellSetIn, FieldOutCell<> cellIndices, FieldOutCell<> edgeIndices); + + typedef void ExecutionSignature(CellShape, InputIndex, PointIndices, VisitIndex, _2, _3); + using InputDomain = _1; + + using ScatterType = vtkm::worklet::ScatterCounting; + VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } + + VTKM_CONT EdgeExtract(const ScatterType& scatter) + : Scatter(scatter) + { + } + + template + VTKM_EXEC void operator()(CellShapeTag cellShape, + CellIndexType cellIndex, + const PointIndexVecType& pointIndices, + vtkm::IdComponent visitIndex, + CellIndexType& cellIndexOut, + EdgeIndexVecType& edgeIndices) const + { + cellIndexOut = cellIndex; + edgeIndices = vtkm::exec::CellEdgeCanonicalId( + pointIndices.GetNumberOfComponents(), visitIndex, cellShape, pointIndices, *this); + }; + +private: + ScatterType Scatter; +}; + +struct CellToCellConnectivity : public vtkm::worklet::WorkletMapField +{ + typedef void ControlSignature(FieldIn<> index, + WholeArrayIn<> cells, + WholeArrayOut<> from, + WholeArrayOut<> to); + + typedef void ExecutionSignature(_1, InputIndex, _2, _3, _4); + using InputDomain = _1; + + template + VTKM_EXEC void operator()(vtkm::Id offset, + vtkm::Id index, + const CellIdPortalType& cells, + ConnectivityPortalType& from, + ConnectivityPortalType& to) const + { + from.Set(index * 2, cells.Get(offset)); + to.Set(index * 2, cells.Get(offset + 1)); + from.Set(index * 2 + 1, cells.Get(offset + 1)); + to.Set(index * 2 + 1, cells.Get(offset)); + } +}; + +template +class CellSetDualGraph +{ +public: + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + + struct degree2 + { + VTKM_EXEC + bool operator()(vtkm::Id degree) const { return degree == 2; } + }; + + template + void EdgeToCellConnectivity(const vtkm::cont::CellSetSingleType& cellSet, + vtkm::cont::ArrayHandle& cellIds, + vtkm::cont::ArrayHandle& cellEdges) const + { + // Get number of edges for each cell and use it as scatter count. + vtkm::cont::ArrayHandle numEdgesPerCell; + vtkm::worklet::DispatcherMapTopology edgesPerCellDisp; + edgesPerCellDisp.Invoke(cellSet, numEdgesPerCell); + + // Get uncompress Cell to Edge mapping + vtkm::worklet::ScatterCounting scatter{ numEdgesPerCell, DeviceAdapter() }; + vtkm::worklet::DispatcherMapTopology edgeExtractDisp{ scatter }; + edgeExtractDisp.Invoke(cellSet, cellIds, cellEdges); + } + + template + void Run(const vtkm::cont::CellSetSingleType& cellSet, + vtkm::cont::ArrayHandle& numIndicesArray, + vtkm::cont::ArrayHandle& indexOffsetArray, + vtkm::cont::ArrayHandle& connectivityArray) const + { + // calculate the uncompressed Edge to Cell connectivity from Point to Cell connectivity + // in the CellSet + vtkm::cont::ArrayHandle cellIds; + vtkm::cont::ArrayHandle cellEdges; + EdgeToCellConnectivity(cellSet, cellIds, cellEdges); + + // sort cell ids by cell edges, this groups cells by cell edges + Algorithm::SortByKey(cellEdges, cellIds); + + // count how many times an edge is shared by cells. + vtkm::cont::ArrayHandle uniqueEdges; + vtkm::cont::ArrayHandle uniqueEdgeDegree; + Algorithm::ReduceByKey( + cellEdges, + vtkm::cont::ArrayHandleConstant(1, cellEdges.GetNumberOfValues()), + uniqueEdges, + uniqueEdgeDegree, + vtkm::Add()); + + // Extract edges shared by two cells + vtkm::cont::ArrayHandle sharedEdges; + Algorithm::CopyIf(uniqueEdges, uniqueEdgeDegree, sharedEdges, degree2()); + + // find shared edges within all the edges. + vtkm::cont::ArrayHandle lb; + Algorithm::LowerBounds(cellEdges, sharedEdges, lb); + + // take each shared edge and the cells to create 2 edges of the dual graph + vtkm::cont::ArrayHandle connFrom; + vtkm::cont::ArrayHandle connTo; + connFrom.Allocate(sharedEdges.GetNumberOfValues() * 2); + connTo.Allocate(sharedEdges.GetNumberOfValues() * 2); + vtkm::worklet::DispatcherMapField c2cDisp; + c2cDisp.Invoke(lb, cellIds, connFrom, connTo); + + // Turn dual graph into Compressed Sparse Row format + Algorithm::SortByKey(connFrom, connTo); + Algorithm::Copy(connTo, connectivityArray); + + vtkm::cont::ArrayHandle dualGraphVertices; + Algorithm::ReduceByKey( + connFrom, + vtkm::cont::ArrayHandleConstant(1, connFrom.GetNumberOfValues()), + dualGraphVertices, + numIndicesArray, + vtkm::Add()); + Algorithm::ScanExclusive(numIndicesArray, indexOffsetArray); + } +}; +#endif //vtk_m_worklet_CellSetDualGraph_h diff --git a/vtkm/worklet/connectivities/GraphConnectivity.h b/vtkm/worklet/connectivities/GraphConnectivity.h new file mode 100644 index 000000000..23168803b --- /dev/null +++ b/vtkm/worklet/connectivities/GraphConnectivity.h @@ -0,0 +1,147 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= + +#ifndef vtk_m_worklet_connectivity_graph_connectivity_h +#define vtk_m_worklet_connectivity_graph_connectivity_h + +#include +#include + +class Graft : public vtkm::worklet::WorkletMapField +{ +public: + typedef void ControlSignature(FieldIn index, + FieldIn start, + FieldIn degree, + WholeArrayIn ids, + WholeArrayInOut comp); + + typedef void ExecutionSignature(_1, _2, _3, _4, _5); + using InputDomain = _1; + + // TODO: Use Scatter? + template + VTKM_EXEC void operator()(vtkm::Id index, + vtkm::Id start, + vtkm::Id degree, + const InPortalType& conn, + InOutPortalType& comp) const + { + for (vtkm::Id offset = start; offset < start + degree; offset++) + { + vtkm::Id neighbor = conn.Get(offset); + if ((comp.Get(index) == comp.Get(comp.Get(index))) && (comp.Get(neighbor) < comp.Get(index))) + { + comp.Set(comp.Get(index), comp.Get(neighbor)); + } + } + } +}; + +class PointerJumping : public vtkm::worklet::WorkletMapField +{ +public: + typedef void ControlSignature(FieldIn index, WholeArrayInOut comp); + typedef void ExecutionSignature(_1, _2); + using InputDomain = _1; + + template + VTKM_EXEC void operator()(vtkm::Id index, InOutPortalType& comp) const + { + // keep updating component id until we reach the root of the tree. + for (auto parent = comp.Get(index); comp.Get(parent) != parent; parent = comp.Get(index)) + { + comp.Set(index, comp.Get(parent)); + } + }; +}; + +class IsStar : public vtkm::worklet::WorkletMapField +{ +public: + typedef void ControlSignature(FieldIn index, WholeArrayIn comp, FieldOut<>); + typedef _3 ExecutionSignature(_1, _2); + using InputDomain = _1; + + template + VTKM_EXEC bool operator()(vtkm::Id index, InOutPortalType& comp) const + { + return comp.Get(index) == comp.Get(comp.Get(index)); + } +}; + +template +class GraphConnectivity +{ +public: + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + + template + void Run(const InputPortalType& numIndexArray, + const InputPortalType& indexOffsetArray, + const InputPortalType& connectivityArray, + OutputPortalType& componentsOut) const + { + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + + bool allStar = false; + vtkm::cont::ArrayHandle components; + vtkm::cont::ArrayHandle isStar; + vtkm::cont::ArrayHandle cellIds; + Algorithm::Copy( + vtkm::cont::ArrayHandleCounting(0, 1, numIndexArray.GetNumberOfValues()), cellIds); + Algorithm::Copy(cellIds, components); + + do + { + vtkm::worklet::DispatcherMapField graftDispatcher; + graftDispatcher.Invoke( + cellIds, indexOffsetArray, numIndexArray, connectivityArray, components); + + // Detection of allStar has to come before pointer jumping. Don't try to rearrange it. + vtkm::worklet::DispatcherMapField isStarDisp; + isStarDisp.Invoke(cellIds, components, isStar); + allStar = Algorithm::Reduce(isStar, true, vtkm::LogicalAnd()); + + vtkm::worklet::DispatcherMapField pointJumpingDispatcher; + pointJumpingDispatcher.Invoke(cellIds, components); + } while (!allStar); + + // renumber connected component to the range of [0, number of components). + vtkm::cont::ArrayHandle uniqueComponents; + Algorithm::Copy(components, uniqueComponents); + Algorithm::Sort(uniqueComponents); + Algorithm::Unique(uniqueComponents); + + vtkm::cont::ArrayHandle uniqueColor; + Algorithm::Copy( + vtkm::cont::ArrayHandleCounting(0, 1, uniqueComponents.GetNumberOfValues()), + uniqueColor); + vtkm::cont::ArrayHandle cellColors; + vtkm::cont::ArrayHandle cellIdsOut; + InnerJoin().Run( + components, cellIds, uniqueComponents, uniqueColor, cellColors, cellIdsOut, componentsOut); + + Algorithm::SortByKey(cellIdsOut, componentsOut); + } +}; +#endif //vtk_m_worklet_connectivity_graph_connectivity_h diff --git a/vtkm/worklet/connectivities/InnerJoin.h b/vtkm/worklet/connectivities/InnerJoin.h new file mode 100644 index 000000000..1044750cc --- /dev/null +++ b/vtkm/worklet/connectivities/InnerJoin.h @@ -0,0 +1,109 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= + +#ifndef vtk_m_worklet_connectivity_InnerJoin_h +#define vtk_m_worklet_connectivity_InnerJoin_h + +#include +#include +#include +#include +#include + +template +class InnerJoin +{ +public: + struct Merge : vtkm::worklet::WorkletMapField + { + typedef void ControlSignature(FieldIn<>, + FieldIn<>, + FieldIn<>, + WholeArrayIn<>, + FieldOut<>, + FieldOut<>, + FieldOut<>); + typedef void ExecutionSignature(_1, _2, _3, VisitIndex, _4, _5, _6, _7); + using InputDomain = _1; + + using ScatterType = vtkm::worklet::ScatterCounting; + + VTKM_CONT + ScatterType GetScatter() const { return this->Scatter; } + + VTKM_CONT + Merge(const ScatterType& scatter) + : Scatter(scatter) + { + } + + // TODO: type trait for array portal? + template + VTKM_EXEC void operator()(KeyType key, + ValueType1 value1, + vtkm::Id lowerBounds, + vtkm::Id visitIndex, + const InPortalType& value2, + vtkm::Id& keyOut, + ValueType1& value1Out, + ValueType2& value2Out) const + { + auto v2 = value2.Get(lowerBounds + visitIndex); + keyOut = key; + value1Out = value1; + value2Out = v2; + } + + private: + ScatterType Scatter; + }; + + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + + // TODO: not mutating input keys and values? + template + void Run(vtkm::cont::ArrayHandle& key1, + vtkm::cont::ArrayHandle& value1, + vtkm::cont::ArrayHandle& key2, + vtkm::cont::ArrayHandle& value2, + vtkm::cont::ArrayHandle& keyOut, + vtkm::cont::ArrayHandle& value1Out, + vtkm::cont::ArrayHandle& value2Out) const + { + Algorithm::SortByKey(key1, value1); + Algorithm::SortByKey(key2, value2); + + vtkm::cont::ArrayHandle lbs; + vtkm::cont::ArrayHandle ubs; + Algorithm::LowerBounds(key2, key1, lbs); + Algorithm::UpperBounds(key2, key1, ubs); + + vtkm::cont::ArrayHandle counts; + Algorithm::Transform(ubs, lbs, counts, vtkm::Subtract()); + + vtkm::worklet::ScatterCounting scatter{ counts, DeviceAdapter() }; + Merge merge(scatter); + vtkm::worklet::DispatcherMapField mergeDisp(merge); + mergeDisp.Invoke(key1, value1, lbs, value2, keyOut, value1Out, value2Out); + }; +}; +#endif //vtk_m_worklet_connectivity_InnerJoin_h diff --git a/vtkm/worklet/contourtree/ActiveEdgeTransferrer.h b/vtkm/worklet/contourtree/ActiveEdgeTransferrer.h index 0a211a092..7285b2f1e 100644 --- a/vtkm/worklet/contourtree/ActiveEdgeTransferrer.h +++ b/vtkm/worklet/contourtree/ActiveEdgeTransferrer.h @@ -108,12 +108,11 @@ public: WholeArrayInOut edgeFar, // (i/o) high end of each edge WholeArrayOut newActiveEdges); // (output) new active edge list typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8); - typedef _1 InputDomain; + using InputDomain = _1; // Passed in constructor because of argument limit on operator - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst - IdPortalType; + using IdPortalType = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst; IdPortalType activeEdges; // (input) active edges IdPortalType prunesTo; // (input) where a vertex prunes to diff --git a/vtkm/worklet/contourtree/ChainDoubler.h b/vtkm/worklet/contourtree/ChainDoubler.h index 741cb64d1..602f1fa2d 100644 --- a/vtkm/worklet/contourtree/ChainDoubler.h +++ b/vtkm/worklet/contourtree/ChainDoubler.h @@ -103,7 +103,7 @@ class ChainDoubler : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn vertexID, WholeArrayInOut chains); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/ChainGraph.h b/vtkm/worklet/contourtree/ChainGraph.h index 390b34ce3..bd4a96b00 100644 --- a/vtkm/worklet/contourtree/ChainGraph.h +++ b/vtkm/worklet/contourtree/ChainGraph.h @@ -134,7 +134,7 @@ template class ChainGraph { public: - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // we will want a reference to the original data array const vtkm::cont::ArrayHandle& values; @@ -386,8 +386,8 @@ void ChainGraph::CompactActiveVertices() std::cout << "=======================" << std::endl; std::cout << std::endl; #endif - typedef vtkm::cont::ArrayHandle IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermuteIndexType; + using IdArrayType = vtkm::cont::ArrayHandle; + using PermuteIndexType = vtkm::cont::ArrayHandlePermutation; // create a temporary array the same size vtkm::cont::ArrayHandle newActiveVertices; @@ -640,10 +640,10 @@ void ChainGraph::DebugPrint(const char* message) std::cout << "---------------------------" << std::endl; std::cout << std::endl; - typedef vtkm::cont::ArrayHandle IdArrayType; - typedef vtkm::cont::ArrayHandle ValueArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermuteIndexType; - typedef vtkm::cont::ArrayHandlePermutation PermuteValueType; + using IdArrayType = vtkm::cont::ArrayHandle; + using ValueArrayType = vtkm::cont::ArrayHandle; + using PermuteIndexType = vtkm::cont::ArrayHandlePermutation; + using PermuteValueType = vtkm::cont::ArrayHandlePermutation; // Full Vertex Arrays vtkm::Id nValues = valueIndex.GetNumberOfValues(); diff --git a/vtkm/worklet/contourtree/ContourTree.h b/vtkm/worklet/contourtree/ContourTree.h index 21783b29a..a86490c0a 100644 --- a/vtkm/worklet/contourtree/ContourTree.h +++ b/vtkm/worklet/contourtree/ContourTree.h @@ -173,12 +173,12 @@ template class ContourTree { public: - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; - typedef vtkm::cont::ArrayHandle IdArrayType; - typedef vtkm::cont::ArrayHandle ValueArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermuteIndexType; - typedef vtkm::cont::ArrayHandlePermutation PermuteValueType; + using IdArrayType = vtkm::cont::ArrayHandle; + using ValueArrayType = vtkm::cont::ArrayHandle; + using PermuteIndexType = vtkm::cont::ArrayHandlePermutation; + using PermuteValueType = vtkm::cont::ArrayHandlePermutation; // reference to the underlying data const vtkm::cont::ArrayHandle values; @@ -248,7 +248,7 @@ public: WholeArrayIn superarcs, FieldOut hasSuperArc); typedef _3 ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; bool vertexIsAssigned; diff --git a/vtkm/worklet/contourtree/CopyJoinSplit.h b/vtkm/worklet/contourtree/CopyJoinSplit.h index b088a61fa..6254d83d8 100644 --- a/vtkm/worklet/contourtree/CopyJoinSplit.h +++ b/vtkm/worklet/contourtree/CopyJoinSplit.h @@ -87,7 +87,7 @@ public: WholeArrayIn outdegree, // (input) WholeArrayOut outbound); // (output) join or split arcs typedef void ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/CopyNeighbors.h b/vtkm/worklet/contourtree/CopyNeighbors.h index 44ac688cf..cf7d2eb9a 100644 --- a/vtkm/worklet/contourtree/CopyNeighbors.h +++ b/vtkm/worklet/contourtree/CopyNeighbors.h @@ -87,7 +87,7 @@ public: WholeArrayIn arcs, // (input) merge tree arcs FieldOut sortVector); // (output) neighbors for active edge typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/CopySupernodes.h b/vtkm/worklet/contourtree/CopySupernodes.h index c0e6376a1..72feb867b 100644 --- a/vtkm/worklet/contourtree/CopySupernodes.h +++ b/vtkm/worklet/contourtree/CopySupernodes.h @@ -90,7 +90,7 @@ public: WholeArrayOut updegree, // (output) compacted updegree WholeArrayOut downdegree); // (output) compacted downdegree typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8, _9); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/DegreeDelta.h b/vtkm/worklet/contourtree/DegreeDelta.h index d6382224a..32407733a 100644 --- a/vtkm/worklet/contourtree/DegreeDelta.h +++ b/vtkm/worklet/contourtree/DegreeDelta.h @@ -85,7 +85,7 @@ public: WholeArrayIn sortVector, // (input) sorted vector of vertices WholeArrayOut candidate); // (output) candidate typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nCandidates; diff --git a/vtkm/worklet/contourtree/DegreeSubrangeOffset.h b/vtkm/worklet/contourtree/DegreeSubrangeOffset.h index 46244ea57..0221d8393 100644 --- a/vtkm/worklet/contourtree/DegreeSubrangeOffset.h +++ b/vtkm/worklet/contourtree/DegreeSubrangeOffset.h @@ -85,7 +85,7 @@ public: WholeArrayIn sortVector, // (input) WholeArrayOut degree); // (output) typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/EdgePeakComparator.h b/vtkm/worklet/contourtree/EdgePeakComparator.h index 9cf89e2d9..9aaee40f8 100644 --- a/vtkm/worklet/contourtree/EdgePeakComparator.h +++ b/vtkm/worklet/contourtree/EdgePeakComparator.h @@ -96,11 +96,10 @@ template class EdgePeakComparator { public: - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst ValuePortalType; - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst - IdPortalType; + using ValuePortalType = typename vtkm::cont::ArrayHandle::template ExecutionTypes< + DeviceAdapter>::PortalConst; + using IdPortalType = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst; ValuePortalType values; IdPortalType valueIndex; diff --git a/vtkm/worklet/contourtree/FillSupernodes.h b/vtkm/worklet/contourtree/FillSupernodes.h index d87d79bad..36723e2b8 100644 --- a/vtkm/worklet/contourtree/FillSupernodes.h +++ b/vtkm/worklet/contourtree/FillSupernodes.h @@ -84,7 +84,7 @@ public: FieldIn downCandidate, // (input) FieldOut isSupernode); // (output) typedef _3 ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/FindLeaves.h b/vtkm/worklet/contourtree/FindLeaves.h index b86d12c8c..9d11a3a2c 100644 --- a/vtkm/worklet/contourtree/FindLeaves.h +++ b/vtkm/worklet/contourtree/FindLeaves.h @@ -88,7 +88,7 @@ public: WholeArrayIn splitArc, // (input) WholeArrayInOut superarc); // (i/o) typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/GoverningSaddleFinder.h b/vtkm/worklet/contourtree/GoverningSaddleFinder.h index 6226b76ea..7c9b550bb 100644 --- a/vtkm/worklet/contourtree/GoverningSaddleFinder.h +++ b/vtkm/worklet/contourtree/GoverningSaddleFinder.h @@ -104,7 +104,7 @@ public: WholeArrayOut prunesTo, // (output) where vertex is pruned to WholeArrayOut outdegree); // (output) updegree of vertex typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/JoinArcConnector.h b/vtkm/worklet/contourtree/JoinArcConnector.h index e8582fe1c..9ea960599 100644 --- a/vtkm/worklet/contourtree/JoinArcConnector.h +++ b/vtkm/worklet/contourtree/JoinArcConnector.h @@ -102,7 +102,7 @@ public: WholeArrayIn saddles, // (input) saddles WholeArrayOut mergeArcs); // (output) target for write back typedef void ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/JoinSuperArcFinder.h b/vtkm/worklet/contourtree/JoinSuperArcFinder.h index 5f14f7ef9..51858a536 100644 --- a/vtkm/worklet/contourtree/JoinSuperArcFinder.h +++ b/vtkm/worklet/contourtree/JoinSuperArcFinder.h @@ -118,7 +118,7 @@ public: WholeArrayInOut saddles, // (in out) saddles WholeArrayInOut extrema); // (in out) maxima typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; bool isJoinTree; diff --git a/vtkm/worklet/contourtree/JoinTreeTransferrer.h b/vtkm/worklet/contourtree/JoinTreeTransferrer.h index 4e51856f8..0e180c591 100644 --- a/vtkm/worklet/contourtree/JoinTreeTransferrer.h +++ b/vtkm/worklet/contourtree/JoinTreeTransferrer.h @@ -106,7 +106,7 @@ public: WholeArrayOut saddles, // (output) saddle array for writing WholeArrayOut arcArray); // (output) arc / max array for writing typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/MergeTree.h b/vtkm/worklet/contourtree/MergeTree.h index 5df4515ed..07251957a 100644 --- a/vtkm/worklet/contourtree/MergeTree.h +++ b/vtkm/worklet/contourtree/MergeTree.h @@ -134,7 +134,7 @@ template class MergeTree { public: - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // original data array const vtkm::cont::ArrayHandle& values; diff --git a/vtkm/worklet/contourtree/Mesh2D_DEM_SaddleStarter.h b/vtkm/worklet/contourtree/Mesh2D_DEM_SaddleStarter.h index f2931b94b..a74b7e698 100644 --- a/vtkm/worklet/contourtree/Mesh2D_DEM_SaddleStarter.h +++ b/vtkm/worklet/contourtree/Mesh2D_DEM_SaddleStarter.h @@ -112,7 +112,7 @@ public: WholeArrayOut edgeFar, // (output) high end of edges WholeArrayOut activeEdges); // (output) active edge list typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8, _9); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nRows; // (input) number of rows in 2D vtkm::Id nCols; // (input) number of cols in 2D diff --git a/vtkm/worklet/contourtree/Mesh2D_DEM_Triangulation.h b/vtkm/worklet/contourtree/Mesh2D_DEM_Triangulation.h index 19a3f8025..773106600 100644 --- a/vtkm/worklet/contourtree/Mesh2D_DEM_Triangulation.h +++ b/vtkm/worklet/contourtree/Mesh2D_DEM_Triangulation.h @@ -109,7 +109,7 @@ template class Mesh2D_DEM_Triangulation { public: - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // original data array const vtkm::cont::ArrayHandle& values; @@ -218,8 +218,8 @@ void Mesh2D_DEM_Triangulation::SetSaddleStarts( // copy the chain maximum from arcArray // : mergeGraph.chainExtremum[vID] = inverseIndex[mergeGraph.arcArray[mergeGraph.valueIndex[vID]]] - typedef vtkm::cont::ArrayHandle IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermuteIndexType; + using IdArrayType = vtkm::cont::ArrayHandle; + using PermuteIndexType = vtkm::cont::ArrayHandlePermutation; vtkm::cont::ArrayHandle tArray; tArray.Allocate(nCriticalPoints); diff --git a/vtkm/worklet/contourtree/Mesh2D_DEM_VertexOutdegreeStarter.h b/vtkm/worklet/contourtree/Mesh2D_DEM_VertexOutdegreeStarter.h index 87bb6c874..d7b05aba6 100644 --- a/vtkm/worklet/contourtree/Mesh2D_DEM_VertexOutdegreeStarter.h +++ b/vtkm/worklet/contourtree/Mesh2D_DEM_VertexOutdegreeStarter.h @@ -103,7 +103,7 @@ public: FieldOut outdegree, // (output) outdegree FieldOut isCritical); // (output) whether critical typedef void ExecutionSignature(_1, _2, _3, _4, _5 /*, _6*/); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nRows; // (input) number of rows in 2D vtkm::Id nCols; // (input) number of cols in 2D diff --git a/vtkm/worklet/contourtree/Mesh2D_DEM_VertexStarter.h b/vtkm/worklet/contourtree/Mesh2D_DEM_VertexStarter.h index 678a630be..80a8890c7 100644 --- a/vtkm/worklet/contourtree/Mesh2D_DEM_VertexStarter.h +++ b/vtkm/worklet/contourtree/Mesh2D_DEM_VertexStarter.h @@ -108,7 +108,7 @@ public: FieldOut chain, // (output) modify the chains FieldOut linkMask); // (output) modify the mask typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nRows; // (input) number of rows in 2D vtkm::Id nCols; // (input) number of cols in 2D diff --git a/vtkm/worklet/contourtree/Mesh3D_DEM_SaddleStarter.h b/vtkm/worklet/contourtree/Mesh3D_DEM_SaddleStarter.h index 46365560f..52430eb2b 100644 --- a/vtkm/worklet/contourtree/Mesh3D_DEM_SaddleStarter.h +++ b/vtkm/worklet/contourtree/Mesh3D_DEM_SaddleStarter.h @@ -114,12 +114,12 @@ public: WholeArrayOut edgeFar, // (output) high end of edges WholeArrayOut activeEdges); // (output) active edge list typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8, _9); - typedef _1 InputDomain; + using InputDomain = _1; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst IdComponentPortalType; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst IdPortalType; + using IdComponentPortalType = typename vtkm::cont::ArrayHandle< + vtkm::IdComponent>::template ExecutionTypes::PortalConst; + using IdPortalType = typename vtkm::cont::ArrayHandle::template ExecutionTypes< + DeviceAdapter>::PortalConst; vtkm::Id nRows; // (input) number of rows in 3D vtkm::Id nCols; // (input) number of cols in 3D diff --git a/vtkm/worklet/contourtree/Mesh3D_DEM_Triangulation.h b/vtkm/worklet/contourtree/Mesh3D_DEM_Triangulation.h index 8b70eed7e..b7d631d55 100644 --- a/vtkm/worklet/contourtree/Mesh3D_DEM_Triangulation.h +++ b/vtkm/worklet/contourtree/Mesh3D_DEM_Triangulation.h @@ -111,7 +111,7 @@ template class Mesh3D_DEM_Triangulation { public: - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; // original data array const vtkm::cont::ArrayHandle& values; @@ -240,8 +240,8 @@ void Mesh3D_DEM_Triangulation::SetSaddleStarts( // copy the chain maximum from arcArray // : mergeGraph.chainExtremum[vID] = inverseIndex[mergeGraph.arcArray[mergeGraph.valueIndex[vID]]] - typedef vtkm::cont::ArrayHandle IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermuteIndexType; + using IdArrayType = vtkm::cont::ArrayHandle; + using PermuteIndexType = vtkm::cont::ArrayHandlePermutation; vtkm::cont::ArrayHandle tArray; tArray.Allocate(nCriticalPoints); diff --git a/vtkm/worklet/contourtree/Mesh3D_DEM_VertexOutdegreeStarter.h b/vtkm/worklet/contourtree/Mesh3D_DEM_VertexOutdegreeStarter.h index c994279f1..661910d36 100644 --- a/vtkm/worklet/contourtree/Mesh3D_DEM_VertexOutdegreeStarter.h +++ b/vtkm/worklet/contourtree/Mesh3D_DEM_VertexOutdegreeStarter.h @@ -105,12 +105,12 @@ public: FieldOut outdegree, // (output) outdegree FieldOut isCritical); // (output) whether critical typedef void ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst IdComponentPortalType; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst IdPortalType; + using IdComponentPortalType = typename vtkm::cont::ArrayHandle< + vtkm::IdComponent>::template ExecutionTypes::PortalConst; + using IdPortalType = typename vtkm::cont::ArrayHandle::template ExecutionTypes< + DeviceAdapter>::PortalConst; vtkm::Id nRows; // (input) number of rows in 3D vtkm::Id nCols; // (input) number of cols in 3D diff --git a/vtkm/worklet/contourtree/Mesh3D_DEM_VertexStarter.h b/vtkm/worklet/contourtree/Mesh3D_DEM_VertexStarter.h index 93f22ef4a..fd5b5d7ca 100644 --- a/vtkm/worklet/contourtree/Mesh3D_DEM_VertexStarter.h +++ b/vtkm/worklet/contourtree/Mesh3D_DEM_VertexStarter.h @@ -109,7 +109,7 @@ public: FieldOut chain, // (output) modify the chains FieldOut linkMask); // (output) modify the mask typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nRows; // (input) number of rows in 3D vtkm::Id nCols; // (input) number of cols in 3D diff --git a/vtkm/worklet/contourtree/RegularPointTransferrer.h b/vtkm/worklet/contourtree/RegularPointTransferrer.h index 8038f1dbd..6927b75b3 100644 --- a/vtkm/worklet/contourtree/RegularPointTransferrer.h +++ b/vtkm/worklet/contourtree/RegularPointTransferrer.h @@ -111,7 +111,7 @@ public: WholeArrayInOut prunesTo, // (i/o) where vertex is pruned to WholeArrayOut outdegree); // (output) updegree of vertex typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; bool isJoinGraph; diff --git a/vtkm/worklet/contourtree/RegularToCandidate.h b/vtkm/worklet/contourtree/RegularToCandidate.h index a389a79ff..e9ad1038a 100644 --- a/vtkm/worklet/contourtree/RegularToCandidate.h +++ b/vtkm/worklet/contourtree/RegularToCandidate.h @@ -86,7 +86,7 @@ public: WholeArrayIn regularToCritical, // (input) sorting indices FieldOut sortVector); // (output) target for write back typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/RegularToCriticalDown.h b/vtkm/worklet/contourtree/RegularToCriticalDown.h index 1dd0c38e9..4c74c6321 100644 --- a/vtkm/worklet/contourtree/RegularToCriticalDown.h +++ b/vtkm/worklet/contourtree/RegularToCriticalDown.h @@ -86,7 +86,7 @@ public: WholeArrayIn regularToCritical, // (input) FieldOut sortVector); // (output) typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/RegularToCriticalUp.h b/vtkm/worklet/contourtree/RegularToCriticalUp.h index dce16af7c..17a2d22c8 100644 --- a/vtkm/worklet/contourtree/RegularToCriticalUp.h +++ b/vtkm/worklet/contourtree/RegularToCriticalUp.h @@ -84,7 +84,7 @@ public: FieldIn candidate, // (input) candidate index WholeArrayOut critical); // (output) typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/ResetDegrees.h b/vtkm/worklet/contourtree/ResetDegrees.h index 11f61b075..368eb6ddf 100644 --- a/vtkm/worklet/contourtree/ResetDegrees.h +++ b/vtkm/worklet/contourtree/ResetDegrees.h @@ -84,7 +84,7 @@ public: WholeArrayOut updegree, // output WholeArrayOut downdegree); // output typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SaddleAscentFunctor.h b/vtkm/worklet/contourtree/SaddleAscentFunctor.h index 60c46a8a0..cb2577f37 100644 --- a/vtkm/worklet/contourtree/SaddleAscentFunctor.h +++ b/vtkm/worklet/contourtree/SaddleAscentFunctor.h @@ -103,7 +103,7 @@ public: WholeArrayInOut edgeFar, // (input) high ends of edges FieldOut newOutdegree); // (output) new updegree of vertex typedef _7 ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SaddleAscentTransferrer.h b/vtkm/worklet/contourtree/SaddleAscentTransferrer.h index 8a5d9d1a2..bf9c27518 100644 --- a/vtkm/worklet/contourtree/SaddleAscentTransferrer.h +++ b/vtkm/worklet/contourtree/SaddleAscentTransferrer.h @@ -101,7 +101,7 @@ public: WholeArrayIn firstEdge, // (input) first edges WholeArrayOut edgeSorter); // (output) edge sorter typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SetJoinAndSplitArcs.h b/vtkm/worklet/contourtree/SetJoinAndSplitArcs.h index fe61ef500..5a5ec5578 100644 --- a/vtkm/worklet/contourtree/SetJoinAndSplitArcs.h +++ b/vtkm/worklet/contourtree/SetJoinAndSplitArcs.h @@ -88,7 +88,7 @@ public: FieldOut joinArc, // (output) FieldOut splitArc); // (output) typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SetSupernodeInward.h b/vtkm/worklet/contourtree/SetSupernodeInward.h index 8602372c2..d29db5111 100644 --- a/vtkm/worklet/contourtree/SetSupernodeInward.h +++ b/vtkm/worklet/contourtree/SetSupernodeInward.h @@ -88,7 +88,7 @@ public: WholeArrayIn outdegree, // (input) WholeArrayInOut superarcs); // (in out) typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SkipVertex.h b/vtkm/worklet/contourtree/SkipVertex.h index d65b33d72..98b9b2c65 100644 --- a/vtkm/worklet/contourtree/SkipVertex.h +++ b/vtkm/worklet/contourtree/SkipVertex.h @@ -86,7 +86,7 @@ public: WholeArrayInOut joinArcs, // (i/o) WholeArrayInOut splitArcs); // (i/o) typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/SubrangeOffset.h b/vtkm/worklet/contourtree/SubrangeOffset.h index 4b568bb94..caf0c3388 100644 --- a/vtkm/worklet/contourtree/SubrangeOffset.h +++ b/vtkm/worklet/contourtree/SubrangeOffset.h @@ -85,7 +85,7 @@ public: WholeArrayIn sortVector, // (input) sorted vector of vertices WholeArrayOut candidate); // (output) candidate typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/TrunkBuilder.h b/vtkm/worklet/contourtree/TrunkBuilder.h index c6842c69b..aa68d4133 100644 --- a/vtkm/worklet/contourtree/TrunkBuilder.h +++ b/vtkm/worklet/contourtree/TrunkBuilder.h @@ -103,7 +103,7 @@ public: WholeArrayIn chainExtremum, // (input) chain extemum for vertices WholeArrayOut prunesTo); // (output) where a vertex prunes to typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/UpdateOutbound.h b/vtkm/worklet/contourtree/UpdateOutbound.h index 565e42959..ae8315006 100644 --- a/vtkm/worklet/contourtree/UpdateOutbound.h +++ b/vtkm/worklet/contourtree/UpdateOutbound.h @@ -84,7 +84,7 @@ public: typedef void ControlSignature(FieldIn superID, // input WholeArrayInOut outbound); // i/o typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/contourtree/VertexDegreeUpdater.h b/vtkm/worklet/contourtree/VertexDegreeUpdater.h index 5bcd17de2..20324763e 100644 --- a/vtkm/worklet/contourtree/VertexDegreeUpdater.h +++ b/vtkm/worklet/contourtree/VertexDegreeUpdater.h @@ -107,7 +107,7 @@ public: WholeArrayInOut chainExtemum, // (i/o) chain extemum for vertices FieldOut newOutdegree); // (output) new updegree of vertex typedef _8 ExecutionSignature(_1, _2, _3, _4, _5, _6, _7); - typedef _1 InputDomain; + using InputDomain = _1; // chainMaximum is safe for I/O here because: // we have previously eliminated maxima from the active vertex list diff --git a/vtkm/worklet/contourtree/VertexMergeComparator.h b/vtkm/worklet/contourtree/VertexMergeComparator.h index 2910bf948..ad6a62edb 100644 --- a/vtkm/worklet/contourtree/VertexMergeComparator.h +++ b/vtkm/worklet/contourtree/VertexMergeComparator.h @@ -101,11 +101,10 @@ template class VertexMergeComparator { public: - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapter>::PortalConst ValuePortalType; - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst - IdPortalType; + using ValuePortalType = typename vtkm::cont::ArrayHandle::template ExecutionTypes< + DeviceAdapter>::PortalConst; + using IdPortalType = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::PortalConst; ValuePortalType values; IdPortalType extrema; diff --git a/vtkm/worklet/cosmotools/ComputeBinIndices.h b/vtkm/worklet/cosmotools/ComputeBinIndices.h index ef67de382..cb2e497f0 100644 --- a/vtkm/worklet/cosmotools/ComputeBinIndices.h +++ b/vtkm/worklet/cosmotools/ComputeBinIndices.h @@ -80,7 +80,7 @@ public: FieldOut binY, FieldOut binZ); typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numBinsX, numBinsY, numBinsZ; // Number of bins each dimension diff --git a/vtkm/worklet/cosmotools/ComputeBinRange.h b/vtkm/worklet/cosmotools/ComputeBinRange.h index e04367f2b..0bba6f180 100644 --- a/vtkm/worklet/cosmotools/ComputeBinRange.h +++ b/vtkm/worklet/cosmotools/ComputeBinRange.h @@ -78,7 +78,7 @@ public: typedef void ControlSignature(FieldIn leftNeighbor, // (input) left neighbor id FieldOut rightNeighbor); // (output) right neighbor id typedef _2 ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id xNum; diff --git a/vtkm/worklet/cosmotools/ComputeBins.h b/vtkm/worklet/cosmotools/ComputeBins.h index 555e9856d..40df22f40 100644 --- a/vtkm/worklet/cosmotools/ComputeBins.h +++ b/vtkm/worklet/cosmotools/ComputeBins.h @@ -84,7 +84,7 @@ public: FieldIn zLoc, // (input) z location in halo FieldOut binId); // (output) bin Id typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; T xMin, xMax, yMin, yMax, zMin, zMax; vtkm::Id xNum, yNum, zNum; diff --git a/vtkm/worklet/cosmotools/ComputeNeighborBins.h b/vtkm/worklet/cosmotools/ComputeNeighborBins.h index f6679d4df..732c8d817 100644 --- a/vtkm/worklet/cosmotools/ComputeNeighborBins.h +++ b/vtkm/worklet/cosmotools/ComputeNeighborBins.h @@ -79,7 +79,7 @@ public: FieldIn binId, // (input) bin Id WholeArrayOut leftNeighbor); // (output) neighbor Id typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id xNum, yNum, zNum; vtkm::Id NUM_NEIGHBORS; diff --git a/vtkm/worklet/cosmotools/ComputePotential.h b/vtkm/worklet/cosmotools/ComputePotential.h index 16dbf16d5..5cda4a0dc 100644 --- a/vtkm/worklet/cosmotools/ComputePotential.h +++ b/vtkm/worklet/cosmotools/ComputePotential.h @@ -89,7 +89,7 @@ public: WholeArrayIn lastParticleId, // (input) last particle in halo FieldOut potential); // (output) bin ID typedef _8 ExecutionSignature(_1, _2, _3, _4, _5, _6, _7); - typedef _1 InputDomain; + using InputDomain = _1; T mass; diff --git a/vtkm/worklet/cosmotools/ComputePotentialBin.h b/vtkm/worklet/cosmotools/ComputePotentialBin.h index 428705bd0..09e5f4346 100644 --- a/vtkm/worklet/cosmotools/ComputePotentialBin.h +++ b/vtkm/worklet/cosmotools/ComputePotentialBin.h @@ -87,7 +87,7 @@ public: FieldInOut bestPot, // (output) best potential estimate FieldInOut worstPot); // (output) worst potential estimate typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nBins; // Number of bins T mass; // Particle mass diff --git a/vtkm/worklet/cosmotools/ComputePotentialMxN.h b/vtkm/worklet/cosmotools/ComputePotentialMxN.h index 185a25abf..57a435f57 100644 --- a/vtkm/worklet/cosmotools/ComputePotentialMxN.h +++ b/vtkm/worklet/cosmotools/ComputePotentialMxN.h @@ -86,7 +86,7 @@ public: WholeArrayIn zLoc, // (input) z location in domain FieldOut potential); // (output) bin ID typedef _6 ExecutionSignature(_1, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nParticles; // Number of particles in halo T mass; // Particle mass diff --git a/vtkm/worklet/cosmotools/ComputePotentialNeighbors.h b/vtkm/worklet/cosmotools/ComputePotentialNeighbors.h index ffeb75e9b..6e23b9e2a 100644 --- a/vtkm/worklet/cosmotools/ComputePotentialNeighbors.h +++ b/vtkm/worklet/cosmotools/ComputePotentialNeighbors.h @@ -90,7 +90,7 @@ public: WholeArrayIn lastParticleId, // (input) last particle in halo FieldOut potential); // (output) bin ID typedef _9 ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id xNum, yNum, zNum; vtkm::Id NUM_NEIGHBORS; diff --git a/vtkm/worklet/cosmotools/ComputePotentialNxN.h b/vtkm/worklet/cosmotools/ComputePotentialNxN.h index 81b0350be..499da422d 100644 --- a/vtkm/worklet/cosmotools/ComputePotentialNxN.h +++ b/vtkm/worklet/cosmotools/ComputePotentialNxN.h @@ -85,7 +85,7 @@ public: WholeArrayIn zLoc, // (input) z location in domain FieldOut potential); // (output) bin ID typedef _5 ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nParticles; // Number of particles in halo T mass; // Particle mass diff --git a/vtkm/worklet/cosmotools/ComputePotentialOnCandidates.h b/vtkm/worklet/cosmotools/ComputePotentialOnCandidates.h index c14930ae6..00d4a38d1 100644 --- a/vtkm/worklet/cosmotools/ComputePotentialOnCandidates.h +++ b/vtkm/worklet/cosmotools/ComputePotentialOnCandidates.h @@ -85,7 +85,7 @@ public: WholeArrayIn zLoc, // (input) z location in domain FieldOut potential); // (output) bin ID typedef _5 ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id nParticles; // Number of particles in halo T mass; // Particle mass diff --git a/vtkm/worklet/cosmotools/EqualsMinimumPotential.h b/vtkm/worklet/cosmotools/EqualsMinimumPotential.h index 054ebf117..51639103a 100644 --- a/vtkm/worklet/cosmotools/EqualsMinimumPotential.h +++ b/vtkm/worklet/cosmotools/EqualsMinimumPotential.h @@ -84,7 +84,7 @@ public: FieldIn potential2, // (input) minimum potential FieldOut minParticleIndx); // (output) particle Id of min typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/cosmotools/GraftParticles.h b/vtkm/worklet/cosmotools/GraftParticles.h index 036ce1730..b1c42c293 100644 --- a/vtkm/worklet/cosmotools/GraftParticles.h +++ b/vtkm/worklet/cosmotools/GraftParticles.h @@ -87,7 +87,7 @@ public: WholeArrayIn lastParticleId, // (input) last particle index vector WholeArrayOut haloId); typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7, _8, _9); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id xNum, yNum, zNum; vtkm::Id NUM_NEIGHBORS; diff --git a/vtkm/worklet/cosmotools/IsStar.h b/vtkm/worklet/cosmotools/IsStar.h index 79673cb89..037ff099f 100644 --- a/vtkm/worklet/cosmotools/IsStar.h +++ b/vtkm/worklet/cosmotools/IsStar.h @@ -80,7 +80,7 @@ public: WholeArrayInOut haloIdLast, WholeArrayInOut<> rootedStar); typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/cosmotools/MarkActiveNeighbors.h b/vtkm/worklet/cosmotools/MarkActiveNeighbors.h index 83a15df43..7f33f78a0 100644 --- a/vtkm/worklet/cosmotools/MarkActiveNeighbors.h +++ b/vtkm/worklet/cosmotools/MarkActiveNeighbors.h @@ -86,7 +86,7 @@ public: WholeArrayIn lastPartId, // (input) vector of last particle indices FieldOut flag); // (output) active bin neighbors mask typedef _8 ExecutionSignature(_1, _2, _3, _4, _5, _6, _7); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id xNum, yNum, zNum; vtkm::Id NUM_NEIGHBORS; diff --git a/vtkm/worklet/cosmotools/PointerJump.h b/vtkm/worklet/cosmotools/PointerJump.h index 66b10920e..fad3558a9 100644 --- a/vtkm/worklet/cosmotools/PointerJump.h +++ b/vtkm/worklet/cosmotools/PointerJump.h @@ -76,7 +76,7 @@ class PointerJump : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn index, WholeArrayInOut D); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT diff --git a/vtkm/worklet/cosmotools/SetCandidateParticles.h b/vtkm/worklet/cosmotools/SetCandidateParticles.h index da575d165..eaa4dcfd2 100644 --- a/vtkm/worklet/cosmotools/SetCandidateParticles.h +++ b/vtkm/worklet/cosmotools/SetCandidateParticles.h @@ -84,7 +84,7 @@ public: FieldIn partCount, // (input) count of particles in bin WholeArrayOut candidate); // (input) z location in bin typedef void ExecutionSignature(_1, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; T cutoffPotential; // Lowest potential for a candidate bin diff --git a/vtkm/worklet/cosmotools/ValidHalo.h b/vtkm/worklet/cosmotools/ValidHalo.h index 28f4686f0..7c558b61b 100644 --- a/vtkm/worklet/cosmotools/ValidHalo.h +++ b/vtkm/worklet/cosmotools/ValidHalo.h @@ -79,7 +79,7 @@ public: WholeArrayIn haloId, FieldOut isValidHalo); typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id pmin; diff --git a/vtkm/worklet/gradient/CellGradient.h b/vtkm/worklet/gradient/CellGradient.h index d288b60d5..85316d939 100644 --- a/vtkm/worklet/gradient/CellGradient.h +++ b/vtkm/worklet/gradient/CellGradient.h @@ -48,7 +48,7 @@ struct CellGradient : vtkm::worklet::WorkletMapPointToCell GradientOutputs outputFields); typedef void ExecutionSignature(CellShape, PointCount, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; template input, FieldOut output); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const InputType& input, OutputType& divergence) const diff --git a/vtkm/worklet/gradient/PointGradient.h b/vtkm/worklet/gradient/PointGradient.h index 6ce4fdff8..364388158 100644 --- a/vtkm/worklet/gradient/PointGradient.h +++ b/vtkm/worklet/gradient/PointGradient.h @@ -50,7 +50,7 @@ struct PointGradient : public vtkm::worklet::WorkletMapCellToPoint GradientOutputs outputFields); typedef void ExecutionSignature(CellCount, CellIndices, WorkIndex, _2, _3, _4, _5); - typedef _1 InputDomain; + using InputDomain = _1; template input, FieldOut output); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const InputType& input, OutputType& qcriterion) const diff --git a/vtkm/worklet/gradient/StructuredPointGradient.h b/vtkm/worklet/gradient/StructuredPointGradient.h index fade0ba06..cc1bd1cec 100644 --- a/vtkm/worklet/gradient/StructuredPointGradient.h +++ b/vtkm/worklet/gradient/StructuredPointGradient.h @@ -48,7 +48,7 @@ struct StructuredPointGradient : public vtkm::worklet::WorkletPointNeighborhood3 typedef void ExecutionSignature(OnBoundary, _2, _3, _4); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::exec::arg::BoundaryState& boundary, diff --git a/vtkm/worklet/gradient/Transpose.h b/vtkm/worklet/gradient/Transpose.h index 430e73eac..314c766fe 100644 --- a/vtkm/worklet/gradient/Transpose.h +++ b/vtkm/worklet/gradient/Transpose.h @@ -42,7 +42,7 @@ struct Transpose3x3 : vtkm::worklet::WorkletMapField typedef void ControlSignature(FieldInOut> field); typedef void ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(FieldInVecType& field) const diff --git a/vtkm/worklet/gradient/Vorticity.h b/vtkm/worklet/gradient/Vorticity.h index e66b2475c..79b091f56 100644 --- a/vtkm/worklet/gradient/Vorticity.h +++ b/vtkm/worklet/gradient/Vorticity.h @@ -40,7 +40,7 @@ struct Vorticity : public vtkm::worklet::WorkletMapField { typedef void ControlSignature(FieldIn input, FieldOut output); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const InputType& input, OutputType& vorticity) const diff --git a/vtkm/worklet/histogram/ComputeNDHistogram.h b/vtkm/worklet/histogram/ComputeNDHistogram.h index bcccd0452..04bc88100 100644 --- a/vtkm/worklet/histogram/ComputeNDHistogram.h +++ b/vtkm/worklet/histogram/ComputeNDHistogram.h @@ -41,7 +41,7 @@ namespace histogram template T compute_delta(T fieldMinValue, T fieldMaxValue, vtkm::Id num) { - typedef vtkm::VecTraits VecType; + using VecType = vtkm::VecTraits; const T fieldRange = fieldMaxValue - fieldMinValue; return fieldRange / static_cast(num); } @@ -56,7 +56,7 @@ class SetHistogramBin : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn<> value, FieldIn<> binIndexIn, FieldOut<> binIndexOut); typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numberOfBins; vtkm::Float64 minValue; @@ -103,7 +103,7 @@ public: template VTKM_CONT void operator()(const vtkm::cont::ArrayHandle& field) const { - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; const vtkm::Vec initValue(field.GetPortalConstControl().Get(0)); vtkm::Vec minMax = Algorithm::Reduce(field, initValue, vtkm::MinAndMax()); @@ -132,7 +132,7 @@ public: FieldOut<> bin1DIndexOut, FieldOut<> oneVariableIndexOut); typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numberOfBins; diff --git a/vtkm/worklet/histogram/MarginalizeNDHistogram.h b/vtkm/worklet/histogram/MarginalizeNDHistogram.h index 28fc4754f..09d91fb3c 100644 --- a/vtkm/worklet/histogram/MarginalizeNDHistogram.h +++ b/vtkm/worklet/histogram/MarginalizeNDHistogram.h @@ -65,7 +65,7 @@ class To1DIndex : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn<> bin, FieldIn<> binIndexIn, FieldOut<> binIndexOut); typedef void ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; vtkm::Id numberOfBins; diff --git a/vtkm/worklet/internal/ClipTables.h b/vtkm/worklet/internal/ClipTables.h index 2d783102d..b364ad03c 100644 --- a/vtkm/worklet/internal/ClipTables.h +++ b/vtkm/worklet/internal/ClipTables.h @@ -19459,7 +19459,7 @@ static vtkm::UInt8 CellEdges[CELL_EDGES_SIZE] = { class ClipTables { public: - typedef vtkm::Vec EdgeVec; + using EdgeVec = vtkm::Vec; template class DevicePortal diff --git a/vtkm/worklet/internal/DispatcherBase.h b/vtkm/worklet/internal/DispatcherBase.h index 7c7ffb885..e684aeb5f 100644 --- a/vtkm/worklet/internal/DispatcherBase.h +++ b/vtkm/worklet/internal/DispatcherBase.h @@ -124,7 +124,7 @@ struct DetermineHasCorrectParameters // control signature as ControlSignature(CellSetIn, ...) and the first argument passed // to Invoke is an ArrayHandle, you will get an error here because you cannot use an // ArrayHandle in place of a CellSetIn argument. (You need to use a CellSet.) See a few - // lines later for some diagnostics to help you trace where the error occured. + // lines later for some diagnostics to help you trace where the error occurred. VTKM_READ_THE_SOURCE_CODE_FOR_HELP(isCorrect); // If you are getting the error described above, the following lines will give you some @@ -161,7 +161,7 @@ struct DispatcherBaseControlSignatureTagCheck // If you get a compile error here, it means there is something that is // not a valid control signature tag in a worklet's ControlSignature. VTKM_IS_CONTROL_SIGNATURE_TAG(ControlSignatureTag); - typedef ControlSignatureTag type; + using type = ControlSignatureTag; }; }; @@ -175,7 +175,7 @@ struct DispatcherBaseExecutionSignatureTagCheck // If you get a compile error here, it means there is something that is not // a valid execution signature tag in a worklet's ExecutionSignature. VTKM_IS_EXECUTION_SIGNATURE_TAG(ExecutionSignatureTag); - typedef ExecutionSignatureTag type; + using type = ExecutionSignatureTag; }; }; @@ -185,8 +185,8 @@ template struct DispatcherBaseTransportInvokeTypes { //Moved out of DispatcherBaseTransportFunctor to reduce code generation - typedef typename ControlInterface::template ParameterType::type ControlSignatureTag; - typedef typename ControlSignatureTag::TransportTag TransportTag; + using ControlSignatureTag = typename ControlInterface::template ParameterType::type; + using TransportTag = typename ControlSignatureTag::TransportTag; }; VTKM_CONT @@ -353,25 +353,25 @@ template class DispatcherBase { private: - typedef DispatcherBase MyType; + using MyType = DispatcherBase; friend struct detail::for_each_dynamic_arg<0>; protected: - typedef vtkm::internal::FunctionInterface - ControlInterface; - typedef vtkm::internal::FunctionInterface - ExecutionInterface; + using ControlInterface = + vtkm::internal::FunctionInterface; + using ExecutionInterface = + vtkm::internal::FunctionInterface; static const vtkm::IdComponent NUM_INVOKE_PARAMS = ControlInterface::ARITY; private: // We don't really need these types, but declaring them checks the arguments // of the control and execution signatures. - typedef typename ControlInterface::template StaticTransformType< - detail::DispatcherBaseControlSignatureTagCheck>::type ControlSignatureCheck; - typedef typename ExecutionInterface::template StaticTransformType< - detail::DispatcherBaseExecutionSignatureTagCheck>::type ExecutionSignatureCheck; + using ControlSignatureCheck = typename ControlInterface::template StaticTransformType< + detail::DispatcherBaseControlSignatureTagCheck>::type; + using ExecutionSignatureCheck = typename ExecutionInterface::template StaticTransformType< + detail::DispatcherBaseExecutionSignatureTagCheck>::type; template VTKM_CONT void StartInvoke(Args&&... args) const @@ -548,16 +548,15 @@ private: // control environment) in a FunctionInterface. Specifically, we use a // static transform of the FunctionInterface to call the transport on each // argument and return the corresponding execution environment object. - typedef typename Invocation::ParameterInterface ParameterInterfaceType; + using ParameterInterfaceType = typename Invocation::ParameterInterface; const ParameterInterfaceType& parameters = invocation.Parameters; - typedef detail::DispatcherBaseTransportFunctor - TransportFunctorType; - typedef - typename ParameterInterfaceType::template StaticTransformType::type - ExecObjectParameters; + using TransportFunctorType = + detail::DispatcherBaseTransportFunctor; + using ExecObjectParameters = + typename ParameterInterfaceType::template StaticTransformType::type; ExecObjectParameters execObjectParameters = parameters.StaticTransformCont( TransportFunctorType(invocation.GetInputDomain(), inputRange, outputRange)); diff --git a/vtkm/worklet/internal/TriangulateTables.h b/vtkm/worklet/internal/TriangulateTables.h index 4eca9979d..67e55b621 100644 --- a/vtkm/worklet/internal/TriangulateTables.h +++ b/vtkm/worklet/internal/TriangulateTables.h @@ -35,8 +35,8 @@ namespace worklet namespace internal { -typedef vtkm::cont::ArrayHandle - TriangulateArrayHandle; +using TriangulateArrayHandle = + vtkm::cont::ArrayHandle; static vtkm::IdComponent TriangleCountData[vtkm::NUMBER_OF_CELL_SHAPES] = { 0, // 0 = vtkm::CELL_SHAPE_EMPTY_CELL @@ -92,7 +92,7 @@ template class TriangulateTablesExecutionObject : public vtkm::exec::ExecutionObjectBase { public: - typedef typename TriangulateArrayHandle::ExecutionTypes::PortalConst PortalType; + using PortalType = typename TriangulateArrayHandle::ExecutionTypes::PortalConst; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC @@ -265,7 +265,7 @@ template class TetrahedralizeTablesExecutionObject : public vtkm::exec::ExecutionObjectBase { public: - typedef typename TriangulateArrayHandle::ExecutionTypes::PortalConst PortalType; + using PortalType = typename TriangulateArrayHandle::ExecutionTypes::PortalConst; VTKM_SUPPRESS_EXEC_WARNINGS VTKM_EXEC diff --git a/vtkm/worklet/internal/WorkletBase.h b/vtkm/worklet/internal/WorkletBase.h index dec54d454..be89c39ca 100644 --- a/vtkm/worklet/internal/WorkletBase.h +++ b/vtkm/worklet/internal/WorkletBase.h @@ -133,63 +133,63 @@ namespace internal class WorkletBase : public vtkm::exec::FunctorBase { public: - typedef vtkm::placeholders::_1 _1; - typedef vtkm::placeholders::_2 _2; - typedef vtkm::placeholders::_3 _3; - typedef vtkm::placeholders::_4 _4; - typedef vtkm::placeholders::_5 _5; - typedef vtkm::placeholders::_6 _6; - typedef vtkm::placeholders::_7 _7; - typedef vtkm::placeholders::_8 _8; - typedef vtkm::placeholders::_9 _9; - typedef vtkm::placeholders::_10 _10; - typedef vtkm::placeholders::_11 _11; - typedef vtkm::placeholders::_12 _12; - typedef vtkm::placeholders::_13 _13; - typedef vtkm::placeholders::_14 _14; - typedef vtkm::placeholders::_15 _15; - typedef vtkm::placeholders::_16 _16; - typedef vtkm::placeholders::_17 _17; - typedef vtkm::placeholders::_18 _18; - typedef vtkm::placeholders::_19 _19; - typedef vtkm::placeholders::_20 _20; + using _1 = vtkm::placeholders::_1; + using _2 = vtkm::placeholders::_2; + using _3 = vtkm::placeholders::_3; + using _4 = vtkm::placeholders::_4; + using _5 = vtkm::placeholders::_5; + using _6 = vtkm::placeholders::_6; + using _7 = vtkm::placeholders::_7; + using _8 = vtkm::placeholders::_8; + using _9 = vtkm::placeholders::_9; + using _10 = vtkm::placeholders::_10; + using _11 = vtkm::placeholders::_11; + using _12 = vtkm::placeholders::_12; + using _13 = vtkm::placeholders::_13; + using _14 = vtkm::placeholders::_14; + using _15 = vtkm::placeholders::_15; + using _16 = vtkm::placeholders::_16; + using _17 = vtkm::placeholders::_17; + using _18 = vtkm::placeholders::_18; + using _19 = vtkm::placeholders::_19; + using _20 = vtkm::placeholders::_20; /// \c ExecutionSignature tag for getting the work index. /// - typedef vtkm::exec::arg::WorkIndex WorkIndex; + using WorkIndex = vtkm::exec::arg::WorkIndex; /// \c ExecutionSignature tag for getting the input index. /// - typedef vtkm::exec::arg::InputIndex InputIndex; + using InputIndex = vtkm::exec::arg::InputIndex; /// \c ExecutionSignature tag for getting the output index. /// - typedef vtkm::exec::arg::OutputIndex OutputIndex; + using OutputIndex = vtkm::exec::arg::OutputIndex; /// \c ExecutionSignature tag for getting the thread indices. /// - typedef vtkm::exec::arg::ThreadIndices ThreadIndices; + using ThreadIndices = vtkm::exec::arg::ThreadIndices; /// \c ExecutionSignature tag for getting the visit index. /// - typedef vtkm::exec::arg::VisitIndex VisitIndex; + using VisitIndex = vtkm::exec::arg::VisitIndex; /// \c ControlSignature tag for execution object inputs. struct ExecObject : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagExecObject TypeCheckTag; - typedef vtkm::cont::arg::TransportTagExecObject TransportTag; - typedef vtkm::exec::arg::FetchTagExecObject FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagExecObject; + using TransportTag = vtkm::cont::arg::TransportTagExecObject; + using FetchTag = vtkm::exec::arg::FetchTagExecObject; }; /// Default input domain is the first argument. Worklet subclasses can /// override this by redefining this type. - typedef _1 InputDomain; + using InputDomain = _1; /// All worklets must define their scatter operation. The scatter defines /// what output each input contributes to. The default scatter is the /// identity scatter (1-to-1 input to output). - typedef vtkm::worklet::ScatterIdentity ScatterType; + using ScatterType = vtkm::worklet::ScatterIdentity; /// In addition to defining the scatter type, the worklet must produce the /// scatter. The default ScatterIdentity has no state, so just return an @@ -201,91 +201,91 @@ public: /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagId IdType; + using IdType = vtkm::TypeListTagId; /// \brief A type list containing the type vtkm::Id2. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagId2 Id2Type; + using Id2Type = vtkm::TypeListTagId2; /// \brief A type list containing the type vtkm::Id3. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagId3 Id3Type; + using Id3Type = vtkm::TypeListTagId3; /// \brief A type list containing the type vtkm::IdComponent. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagIdComponent IdComponentType; + using IdComponentType = vtkm::TypeListTagIdComponent; /// \brief A list of types commonly used for indexing. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagIndex Index; + using Index = vtkm::TypeListTagIndex; /// \brief A list of types commonly used for scalar fields. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagFieldScalar Scalar; + using Scalar = vtkm::TypeListTagFieldScalar; /// \brief A list of all basic types used for scalar fields. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagScalarAll ScalarAll; + using ScalarAll = vtkm::TypeListTagScalarAll; /// \brief A list of types commonly used for vector fields of 2 components. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagFieldVec2 Vec2; + using Vec2 = vtkm::TypeListTagFieldVec2; /// \brief A list of types commonly used for vector fields of 3 components. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagFieldVec3 Vec3; + using Vec3 = vtkm::TypeListTagFieldVec3; /// \brief A list of types commonly used for vector fields of 4 components. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagFieldVec4 Vec4; + using Vec4 = vtkm::TypeListTagFieldVec4; /// \brief A list of all basic types used for vector fields. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagVecAll VecAll; + using VecAll = vtkm::TypeListTagVecAll; /// \brief A list of types (scalar and vector) commonly used in fields. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagField FieldCommon; + using FieldCommon = vtkm::TypeListTagField; /// \brief A list of vector types commonly used in fields. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagVecCommon VecCommon; + using VecCommon = vtkm::TypeListTagVecCommon; /// \brief A list of generally common types. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagCommon CommonTypes; + using CommonTypes = vtkm::TypeListTagCommon; /// \brief A list of all basic types. /// /// This is a convenience type to use as template arguments to \c /// ControlSignature tags to specify the types of worklet arguments. - typedef vtkm::TypeListTagAll AllTypes; + using AllTypes = vtkm::TypeListTagAll; /// \c ControlSignature tag for whole input arrays. /// @@ -300,9 +300,9 @@ public: template struct WholeArrayIn : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagWholeArrayIn TransportTag; - typedef vtkm::exec::arg::FetchTagExecObject FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagWholeArrayIn; + using FetchTag = vtkm::exec::arg::FetchTagExecObject; }; /// \c ControlSignature tag for whole output arrays. @@ -319,9 +319,9 @@ public: template struct WholeArrayOut : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagWholeArrayOut TransportTag; - typedef vtkm::exec::arg::FetchTagExecObject FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagWholeArrayOut; + using FetchTag = vtkm::exec::arg::FetchTagExecObject; }; /// \c ControlSignature tag for whole input/output arrays. @@ -339,9 +339,9 @@ public: template struct WholeArrayInOut : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagWholeArrayInOut TransportTag; - typedef vtkm::exec::arg::FetchTagExecObject FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagArray; + using TransportTag = vtkm::cont::arg::TransportTagWholeArrayInOut; + using FetchTag = vtkm::exec::arg::FetchTagExecObject; }; /// \c ControlSignature tag for whole input/output arrays. @@ -359,9 +359,9 @@ public: template struct AtomicArrayInOut : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagAtomicArray TypeCheckTag; - typedef vtkm::cont::arg::TransportTagAtomicArray TransportTag; - typedef vtkm::exec::arg::FetchTagExecObject FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagAtomicArray; + using TransportTag = vtkm::cont::arg::TransportTagAtomicArray; + using FetchTag = vtkm::exec::arg::FetchTagExecObject; }; /// \c ControlSignature tag for whole input topology. @@ -377,9 +377,9 @@ public: template struct WholeCellSetIn : vtkm::cont::arg::ControlSignatureTagBase { - typedef vtkm::cont::arg::TypeCheckTagCellSet TypeCheckTag; - typedef vtkm::cont::arg::TransportTagCellSetIn TransportTag; - typedef vtkm::exec::arg::FetchTagWholeCellSetIn FetchTag; + using TypeCheckTag = vtkm::cont::arg::TypeCheckTagCellSet; + using TransportTag = vtkm::cont::arg::TransportTagCellSetIn; + using FetchTag = vtkm::exec::arg::FetchTagWholeCellSetIn; }; /// \brief Creates a \c ThreadIndices object. diff --git a/vtkm/worklet/internal/testing/UnitTestDispatcherBase.cxx b/vtkm/worklet/internal/testing/UnitTestDispatcherBase.cxx index b28016de2..20efebee7 100644 --- a/vtkm/worklet/internal/testing/UnitTestDispatcherBase.cxx +++ b/vtkm/worklet/internal/testing/UnitTestDispatcherBase.cxx @@ -29,7 +29,7 @@ namespace { -typedef vtkm::cont::DeviceAdapterTagSerial Device; +using Device = vtkm::cont::DeviceAdapterTagSerial; static const vtkm::Id ARRAY_SIZE = 10; diff --git a/vtkm/worklet/particleadvection/GridEvaluators.h b/vtkm/worklet/particleadvection/GridEvaluators.h index 56fb0be19..1bc555eb6 100644 --- a/vtkm/worklet/particleadvection/GridEvaluators.h +++ b/vtkm/worklet/particleadvection/GridEvaluators.h @@ -130,7 +130,7 @@ private: template class UniformGridEvaluate { - typedef vtkm::cont::ArrayHandle> FieldHandle; + using FieldHandle = vtkm::cont::ArrayHandle>; public: VTKM_CONT @@ -143,10 +143,10 @@ public: { vectors = vectorField.PrepareForInput(DeviceAdapterTag()); - typedef vtkm::cont::ArrayHandleUniformPointCoordinates UniformType; - typedef vtkm::cont::CellSetStructured<3> StructuredType; + using UniformType = vtkm::cont::ArrayHandleUniformPointCoordinates; + using StructuredType = vtkm::cont::CellSetStructured<3>; - if (!coords.GetData().IsSameType()) + if (!coords.GetData().IsType()) throw vtkm::cont::ErrorInternal("Coordinates are not uniform."); if (!cellSet.IsSameType(StructuredType())) throw vtkm::cont::ErrorInternal("Cells are not 3D structured."); @@ -174,10 +174,10 @@ public: VTKM_CONT UniformGridEvaluate(const vtkm::cont::DataSet& ds) { - typedef vtkm::cont::ArrayHandleUniformPointCoordinates UniformType; + using UniformType = vtkm::cont::ArrayHandleUniformPointCoordinates; auto coordArray = ds.GetCoordinateSystem().GetData(); - if (!coordArray.IsSameType()) + if (!coordArray.IsType()) throw vtkm::cont::ErrorInternal("Given dataset is was not uniform."); bounds = ds.GetCoordinateSystem(0).GetBounds(); @@ -311,7 +311,7 @@ private: template class RectilinearGridEvaluate { - typedef vtkm::cont::ArrayHandle> FieldHandle; + using FieldHandle = vtkm::cont::ArrayHandle>; public: VTKM_CONT @@ -319,9 +319,9 @@ public: const vtkm::cont::DynamicCellSet& cellSet, const FieldHandle& vectorField) { - typedef vtkm::cont::CellSetStructured<3> StructuredType; + using StructuredType = vtkm::cont::CellSetStructured<3>; - if (!coords.GetData().IsSameType()) + if (!coords.GetData().IsType()) throw vtkm::cont::ErrorInternal("Coordinates are not rectilinear."); if (!cellSet.IsSameType(StructuredType())) throw vtkm::cont::ErrorInternal("Cells are not 3D structured."); @@ -352,7 +352,7 @@ public: planeSize = dims[0] * dims[1]; rowSize = dims[0]; auto coordArray = dataset.GetCoordinateSystem().GetData(); - if (coordArray.IsSameType()) + if (coordArray.IsType()) { RectilinearType gridPoints = coordArray.Cast(); xAxis = gridPoints.GetPortalConstControl().GetFirstPortal(); @@ -492,11 +492,11 @@ public: } private: - typedef vtkm::cont::ArrayHandle AxisHandle; - typedef vtkm::cont::ArrayHandleCartesianProduct - RectilinearType; - typedef typename RectilinearType::template ExecutionTypes::PortalConst - RectilinearConstPortal; + using AxisHandle = vtkm::cont::ArrayHandle; + using RectilinearType = + vtkm::cont::ArrayHandleCartesianProduct; + using RectilinearConstPortal = + typename RectilinearType::template ExecutionTypes::PortalConst; typename AxisHandle::template ExecutionTypes::PortalConst xAxis; typename AxisHandle::template ExecutionTypes::PortalConst yAxis; typename AxisHandle::template ExecutionTypes::PortalConst zAxis; diff --git a/vtkm/worklet/particleadvection/ParticleAdvectionWorklets.h b/vtkm/worklet/particleadvection/ParticleAdvectionWorklets.h index 97cf9d746..0ff2c7b3e 100644 --- a/vtkm/worklet/particleadvection/ParticleAdvectionWorklets.h +++ b/vtkm/worklet/particleadvection/ParticleAdvectionWorklets.h @@ -44,7 +44,7 @@ class ParticleAdvectWorklet : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn idx, ExecObject ic); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::Id& idx, IntegralCurveType& ic) const @@ -86,11 +86,11 @@ template DeviceAlgorithm; - typedef vtkm::worklet::particleadvection::ParticleAdvectWorklet - ParticleAdvectWorkletType; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; + using ParticleAdvectWorkletType = + vtkm::worklet::particleadvection::ParticleAdvectWorklet; ParticleAdvectionWorklet() {} @@ -139,14 +139,14 @@ template > FieldHandle; - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; - typedef typename FieldHandle::template ExecutionTypes::PortalConst - FieldPortalConstType; - typedef vtkm::worklet::particleadvection::ParticleAdvectWorklet - ParticleAdvectWorkletType; + using FieldHandle = vtkm::cont::ArrayHandle>; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; + using FieldPortalConstType = + typename FieldHandle::template ExecutionTypes::PortalConst; + using ParticleAdvectWorkletType = + vtkm::worklet::particleadvection::ParticleAdvectWorklet; StreamlineWorklet() {} @@ -183,10 +183,10 @@ private: vtkm::cont::ArrayHandle& status, vtkm::cont::ArrayHandle& stepsTaken) { - typedef typename vtkm::worklet::DispatcherMapField - ParticleWorkletDispatchType; - typedef vtkm::worklet::particleadvection::StateRecordingParticles - StreamlineType; + using ParticleWorkletDispatchType = + typename vtkm::worklet::DispatcherMapField; + using StreamlineType = + vtkm::worklet::particleadvection::StateRecordingParticles; vtkm::Id numSeeds = static_cast(seedArray.GetNumberOfValues()); diff --git a/vtkm/worklet/particleadvection/Particles.h b/vtkm/worklet/particleadvection/Particles.h index 8a86dd440..51d011e44 100644 --- a/vtkm/worklet/particleadvection/Particles.h +++ b/vtkm/worklet/particleadvection/Particles.h @@ -48,11 +48,10 @@ class Particles : public vtkm::exec::ExecutionObjectBase { private: - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - IdPortal; - typedef typename vtkm::cont::ArrayHandle>::template ExecutionTypes< - DeviceAdapterTag>::Portal PosPortal; + using IdPortal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; + using PosPortal = typename vtkm::cont::ArrayHandle>::template ExecutionTypes< + DeviceAdapterTag>::Portal; public: VTKM_EXEC_CONT @@ -207,13 +206,12 @@ class StateRecordingParticles : public Particles { private: - typedef - typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal - IdPortal; - typedef typename vtkm::cont::ArrayHandle::template ExecutionTypes< - DeviceAdapterTag>::Portal IdComponentPortal; - typedef typename vtkm::cont::ArrayHandle>::template ExecutionTypes< - DeviceAdapterTag>::Portal PosPortal; + using IdPortal = + typename vtkm::cont::ArrayHandle::template ExecutionTypes::Portal; + using IdComponentPortal = typename vtkm::cont::ArrayHandle< + vtkm::IdComponent>::template ExecutionTypes::Portal; + using PosPortal = typename vtkm::cont::ArrayHandle>::template ExecutionTypes< + DeviceAdapterTag>::Portal; public: VTKM_EXEC_CONT diff --git a/vtkm/worklet/spatialstructure/KdTree3DConstruction.h b/vtkm/worklet/spatialstructure/KdTree3DConstruction.h index 356d02531..f0d88d0c9 100644 --- a/vtkm/worklet/spatialstructure/KdTree3DConstruction.h +++ b/vtkm/worklet/spatialstructure/KdTree3DConstruction.h @@ -238,7 +238,7 @@ public: BinaryFunctor binary_functor, DeviceAdapter vtkmNotUsed(device)) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle resultHandle; @@ -337,7 +337,7 @@ public: vtkm::cont::ArrayHandle& segIdHandle, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle segCountAryHandle; { @@ -363,7 +363,7 @@ public: vtkm::cont::ArrayHandle& C_Handle, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle D_Handle; T initValue = 0; @@ -400,7 +400,7 @@ public: vtkm::cont::ArrayHandle& D_Handle, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::Id nPoints = A_Handle.GetNumberOfValues(); @@ -464,7 +464,7 @@ public: vtkm::cont::ArrayHandle& Z_Handle, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle D_Handle; T initValue = 0; @@ -518,7 +518,7 @@ public: vtkm::Int32 level, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandle flag_Handle; if (level % 3 == 0) @@ -581,7 +581,7 @@ public: vtkm::cont::ArrayHandle& splitId_Handle, DeviceAdapter device) { - typedef typename vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::Id nTrainingPoints = coordi_Handle.GetNumberOfValues(); vtkm::cont::ArrayHandleCounting counting_Handle(0, 1, nTrainingPoints); diff --git a/vtkm/worklet/splatkernels/Gaussian.h b/vtkm/worklet/splatkernels/Gaussian.h index e9639175c..03cd92f8e 100644 --- a/vtkm/worklet/splatkernels/Gaussian.h +++ b/vtkm/worklet/splatkernels/Gaussian.h @@ -24,7 +24,7 @@ // // Gaussian kernel. -// Compact support is achived by truncating the kernel beyond the cutoff radius +// Compact support is achieved by truncating the kernel beyond the cutoff radius // This implementation uses a factor of 5 between smoothing length and cutoff // diff --git a/vtkm/worklet/splatkernels/KernelBase.h b/vtkm/worklet/splatkernels/KernelBase.h index 47e1f0efb..143884bd7 100644 --- a/vtkm/worklet/splatkernels/KernelBase.h +++ b/vtkm/worklet/splatkernels/KernelBase.h @@ -31,7 +31,7 @@ namespace splatkernels { // Vector class used in the kernels -typedef vtkm::Vec vector_type; +using vector_type = vtkm::Vec; // Pi compatibility #ifndef M_PI #define M_PI vtkm::Pi() diff --git a/vtkm/worklet/testing/CMakeLists.txt b/vtkm/worklet/testing/CMakeLists.txt index 2d1853a25..8de229652 100644 --- a/vtkm/worklet/testing/CMakeLists.txt +++ b/vtkm/worklet/testing/CMakeLists.txt @@ -23,6 +23,8 @@ set(unit_tests UnitTestCellAverage.cxx UnitTestCellDeepCopy.cxx UnitTestCellGradient.cxx + UnitTestCellSetConnectivity.cpp + UnitTestCellSetDualGraph.cxx UnitTestClipping.cxx UnitTestContourTreeUniform.cxx UnitTestCosmoTools.cxx @@ -34,6 +36,7 @@ set(unit_tests UnitTestExtractStructured.cxx UnitTestFieldHistogram.cxx UnitTestFieldStatistics.cxx + UnitTestInnerJoin.cxx UnitTestKdTreeBuildNNS.cxx UnitTestKeys.cxx UnitTestMagnitude.cxx @@ -47,7 +50,9 @@ set(unit_tests UnitTestParticleAdvection.cxx UnitTestPointElevation.cxx UnitTestPointGradient.cxx + UnitTestProbe.cxx UnitTestRemoveUnusedPoints.cxx + UnitTestScalarsToColors.cxx UnitTestScatterCounting.cxx UnitTestScatterPermutation.cxx UnitTestSplatKernels.cxx diff --git a/vtkm/worklet/testing/UnitTestCellSetConnectivity.cpp b/vtkm/worklet/testing/UnitTestCellSetConnectivity.cpp new file mode 100644 index 000000000..e5b5fa547 --- /dev/null +++ b/vtkm/worklet/testing/UnitTestCellSetConnectivity.cpp @@ -0,0 +1,154 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#include +#include +#include + +#include + +class TangleField : public vtkm::worklet::WorkletMapField +{ +public: + typedef void ControlSignature(FieldIn vertexId, FieldOut v); + typedef void ExecutionSignature(_1, _2); + using InputDomain = _1; + + const vtkm::Id xdim, ydim, zdim; + const vtkm::FloatDefault xmin, ymin, zmin, xmax, ymax, zmax; + const vtkm::Id cellsPerLayer; + + VTKM_CONT + TangleField(const vtkm::Id3 dims, + const vtkm::FloatDefault mins[3], + const vtkm::FloatDefault maxs[3]) + : xdim(dims[0]) + , ydim(dims[1]) + , zdim(dims[2]) + , xmin(mins[0]) + , ymin(mins[1]) + , zmin(mins[2]) + , xmax(maxs[0]) + , ymax(maxs[1]) + , zmax(maxs[2]) + , cellsPerLayer((xdim) * (ydim)) + { + } + + VTKM_EXEC + void operator()(const vtkm::Id& vertexId, vtkm::Float32& v) const + { + const vtkm::Id x = vertexId % (xdim); + const vtkm::Id y = (vertexId / (xdim)) % (ydim); + const vtkm::Id z = vertexId / cellsPerLayer; + + const vtkm::FloatDefault fx = + static_cast(x) / static_cast(xdim - 1); + const vtkm::FloatDefault fy = + static_cast(y) / static_cast(xdim - 1); + const vtkm::FloatDefault fz = + static_cast(z) / static_cast(xdim - 1); + + const vtkm::Float32 xx = 3.0f * vtkm::Float32(xmin + (xmax - xmin) * (fx)); + const vtkm::Float32 yy = 3.0f * vtkm::Float32(ymin + (ymax - ymin) * (fy)); + const vtkm::Float32 zz = 3.0f * vtkm::Float32(zmin + (zmax - zmin) * (fz)); + + v = (xx * xx * xx * xx - 5.0f * xx * xx + yy * yy * yy * yy - 5.0f * yy * yy + + zz * zz * zz * zz - 5.0f * zz * zz + 11.8f) * + 0.2f + + 0.5f; + } +}; + +static vtkm::cont::DataSet MakeIsosurfaceTestDataSet(vtkm::Id3 dims) +{ + vtkm::cont::DataSet dataSet; + + const vtkm::Id3 vdims(dims[0] + 1, dims[1] + 1, dims[2] + 1); + + vtkm::FloatDefault mins[3] = { -1.0f, -1.0f, -1.0f }; + vtkm::FloatDefault maxs[3] = { 1.0f, 1.0f, 1.0f }; + + vtkm::cont::ArrayHandle pointFieldArray; + vtkm::cont::ArrayHandleIndex vertexCountImplicitArray(vdims[0] * vdims[1] * vdims[2]); + vtkm::worklet::DispatcherMapField tangleFieldDispatcher( + TangleField(vdims, mins, maxs)); + tangleFieldDispatcher.Invoke(vertexCountImplicitArray, pointFieldArray); + + vtkm::Id numCells = dims[0] * dims[1] * dims[2]; + auto cellFieldArray = vtkm::cont::make_ArrayHandleCounting(0, 1, numCells); + + vtkm::Vec origin(0.0f, 0.0f, 0.0f); + vtkm::Vec spacing(1.0f / static_cast(dims[0]), + 1.0f / static_cast(dims[2]), + 1.0f / static_cast(dims[1])); + + vtkm::cont::ArrayHandleUniformPointCoordinates coordinates(vdims, origin, spacing); + dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates)); + + static const vtkm::IdComponent ndim = 3; + vtkm::cont::CellSetStructured cellSet("cells"); + cellSet.SetPointDimensions(vdims); + dataSet.AddCellSet(cellSet); + + dataSet.AddField(vtkm::cont::Field("nodevar", vtkm::cont::Field::ASSOC_POINTS, pointFieldArray)); + dataSet.AddField( + vtkm::cont::Field("cellvar", vtkm::cont::Field::ASSOC_CELL_SET, "cells", cellFieldArray)); + + return dataSet; +} + + +template +class TestCellSetConnectivity +{ +public: + void TestTangleIsosurface() const + { + vtkm::Id3 dims(4, 4, 4); + vtkm::cont::DataSet dataSet = MakeIsosurfaceTestDataSet(dims); + + vtkm::filter::MarchingCubes filter; + filter.SetGenerateNormals(true); + filter.SetMergeDuplicatePoints(true); + filter.SetIsoValue(0, 0.1); + vtkm::filter::Result result = filter.Execute(dataSet, dataSet.GetField("nodevar")); + vtkm::cont::DataSet& outputData = result.GetDataSet(); + + auto cellSet = outputData.GetCellSet().Cast>(); + vtkm::cont::ArrayHandle componentArray; + CellSetConnectivity().Run(cellSet, componentArray, DeviceAdapter()); + + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + Algorithm::Sort(componentArray); + Algorithm::Unique(componentArray); + VTKM_TEST_ASSERT(componentArray.GetNumberOfValues() == 8, + "Wrong number of connected components"); + } + + void operator()() const { this->TestTangleIsosurface(); } +}; + +int UnitTestCellSetConnectivity(int, char* []) +{ + return vtkm::cont::testing::Testing::Run( + TestCellSetConnectivity()); +} diff --git a/vtkm/worklet/testing/UnitTestCellSetDualGraph.cxx b/vtkm/worklet/testing/UnitTestCellSetDualGraph.cxx new file mode 100644 index 000000000..55195c9e0 --- /dev/null +++ b/vtkm/worklet/testing/UnitTestCellSetDualGraph.cxx @@ -0,0 +1,88 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= +#include +#include +#include + +#include + +template +class TestCellSetDualGraph +{ +public: + template + bool TestArrayHandle(const vtkm::cont::ArrayHandle& ah, + const T* expected, + vtkm::Id size) const + { + if (size != ah.GetNumberOfValues()) + { + return false; + } + + for (vtkm::Id i = 0; i < size; ++i) + { + if (ah.GetPortalConstControl().Get(i) != expected[i]) + { + return false; + } + } + + return true; + } + + void TestTriangleMesh() const + { + std::vector connectivity = { 0, 2, 4, 1, 3, 5, 2, 6, 4, 5, 3, 7, 2, 9, 6, 4, 6, 8 }; + + vtkm::cont::CellSetSingleType<> cellSet; + cellSet.Fill(8, vtkm::CELL_SHAPE_TRIANGLE, 3, vtkm::cont::make_ArrayHandle(connectivity)); + + vtkm::cont::ArrayHandle numIndicesArray; + vtkm::cont::ArrayHandle indexOffsetArray; + vtkm::cont::ArrayHandle connectivityArray; + + CellSetDualGraph().Run( + cellSet, numIndicesArray, indexOffsetArray, connectivityArray); + + vtkm::Id expectedNumIndices[] = { 1, 1, 3, 1, 1, 1 }; + VTKM_TEST_ASSERT(numIndicesArray.GetNumberOfValues() == 6, + "Wrong number of elements in NumIndices array"); + VTKM_TEST_ASSERT(TestArrayHandle(numIndicesArray, expectedNumIndices, 6), + "Got incorrect numIndices"); + + vtkm::Id expectedIndexOffset[] = { 0, 1, 2, 5, 6, 7 }; + VTKM_TEST_ASSERT(TestArrayHandle(indexOffsetArray, expectedIndexOffset, 6), + "Got incorrect indexOffset"); + + vtkm::Id expectedConnectivity[] = { 2, 3, 0, 4, 5, 1, 2, 2 }; + VTKM_TEST_ASSERT(TestArrayHandle(connectivityArray, expectedConnectivity, 8), + "Got incorrect dual graph connectivity"); + } + + void operator()() const { this->TestTriangleMesh(); } +}; + +int UnitTestCellSetDualGraph(int, char* []) +{ + return vtkm::cont::testing::Testing::Run(TestCellSetDualGraph()); +} diff --git a/vtkm/worklet/testing/UnitTestClipping.cxx b/vtkm/worklet/testing/UnitTestClipping.cxx index 7e928bd5a..a60ea2bb5 100644 --- a/vtkm/worklet/testing/UnitTestClipping.cxx +++ b/vtkm/worklet/testing/UnitTestClipping.cxx @@ -35,7 +35,7 @@ #include -typedef vtkm::Vec Coord3D; +using Coord3D = vtkm::Vec; const vtkm::Float32 clipValue = 0.5; diff --git a/vtkm/worklet/testing/UnitTestCosmoTools.cxx b/vtkm/worklet/testing/UnitTestCosmoTools.cxx index 3693d85d6..0c7175246 100644 --- a/vtkm/worklet/testing/UnitTestCosmoTools.cxx +++ b/vtkm/worklet/testing/UnitTestCosmoTools.cxx @@ -130,7 +130,7 @@ vtkm::cont::DataSet MakeCosmo_3DDataSet_0() // Coordinates const int nVerts = 14; const int nCells = 14; - typedef vtkm::Vec CoordType; + using CoordType = vtkm::Vec; std::vector coords(nVerts); coords[0] = CoordType(20.8125f, 10.8864f, 0.309784f); diff --git a/vtkm/worklet/testing/UnitTestCrossProduct.cxx b/vtkm/worklet/testing/UnitTestCrossProduct.cxx index 694d1b7e0..6d10d275a 100644 --- a/vtkm/worklet/testing/UnitTestCrossProduct.cxx +++ b/vtkm/worklet/testing/UnitTestCrossProduct.cxx @@ -88,7 +88,7 @@ void TestCrossProduct() VTKM_TEST_ASSERT(outputArray.GetNumberOfValues() == inputArray1.GetNumberOfValues(), "Wrong number of results for CrossProduct worklet"); - //Test the cannonical cases. + //Test the canonical cases. VTKM_TEST_ASSERT( test_equal(outputArray.GetPortalConstControl().Get(0), vtkm::make_Vec(0, 0, 1)) && test_equal(outputArray.GetPortalConstControl().Get(1), vtkm::make_Vec(1, 0, 0)) && diff --git a/vtkm/worklet/testing/UnitTestExternalFaces.cxx b/vtkm/worklet/testing/UnitTestExternalFaces.cxx index 634976f08..28e377676 100644 --- a/vtkm/worklet/testing/UnitTestExternalFaces.cxx +++ b/vtkm/worklet/testing/UnitTestExternalFaces.cxx @@ -79,7 +79,7 @@ void TestExternalFaces1() //--------------Construct a VTK-m Test Dataset---------------- const int nVerts = 8; //A cube that is tetrahedralized - typedef vtkm::Vec CoordType; + using CoordType = vtkm::Vec; vtkm::cont::ArrayHandle coordinates; coordinates.Allocate(nVerts); coordinates.GetPortalControl().Set(0, CoordType(0.0f, 0.0f, 0.0f)); diff --git a/vtkm/worklet/testing/UnitTestExtractGeometry.cxx b/vtkm/worklet/testing/UnitTestExtractGeometry.cxx index c1af77958..2ab60372f 100644 --- a/vtkm/worklet/testing/UnitTestExtractGeometry.cxx +++ b/vtkm/worklet/testing/UnitTestExtractGeometry.cxx @@ -34,8 +34,8 @@ public: { std::cout << "Testing extract cell explicit by id:" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); @@ -67,7 +67,7 @@ public: { std::cout << "Testing extract cells with implicit function (box) on explicit:" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); @@ -109,8 +109,8 @@ public: { std::cout << "Testing extract cells structured by id:" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created @@ -143,8 +143,8 @@ public: { std::cout << "Testing extract cells structured by id:" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -176,7 +176,7 @@ public: { std::cout << "Testing extract cells with implicit function (box):" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -217,7 +217,7 @@ public: { std::cout << "Testing extract cells with implicit function (sphere):" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); diff --git a/vtkm/worklet/testing/UnitTestExtractPoints.cxx b/vtkm/worklet/testing/UnitTestExtractPoints.cxx index 3227aad52..430c876b1 100644 --- a/vtkm/worklet/testing/UnitTestExtractPoints.cxx +++ b/vtkm/worklet/testing/UnitTestExtractPoints.cxx @@ -33,7 +33,7 @@ public: { std::cout << "Testing extract points structured by id:" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -60,7 +60,7 @@ public: { std::cout << "Testing extract points with implicit function (box):" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -92,7 +92,7 @@ public: { std::cout << "Testing extract points with implicit function (box):" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -124,7 +124,7 @@ public: { std::cout << "Testing extract points with implicit function (sphere):" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -156,7 +156,7 @@ public: { std::cout << "Testing extract points with implicit function (box) on explicit:" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); @@ -188,7 +188,7 @@ public: { std::cout << "Testing extract points with implicit function (box) on explicit:" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); @@ -220,7 +220,7 @@ public: { std::cout << "Testing extract points explicit by id:" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); diff --git a/vtkm/worklet/testing/UnitTestExtractStructured.cxx b/vtkm/worklet/testing/UnitTestExtractStructured.cxx index b89407423..5f24497f4 100644 --- a/vtkm/worklet/testing/UnitTestExtractStructured.cxx +++ b/vtkm/worklet/testing/UnitTestExtractStructured.cxx @@ -33,7 +33,7 @@ public: void TestUniform2D() const { std::cout << "Testing extract structured uniform 2D" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DUniformDataSet1(); @@ -57,7 +57,7 @@ public: void TestUniform3D() const { std::cout << "Testing extract structured uniform 3D" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DUniformDataSet1(); @@ -122,7 +122,7 @@ public: void TestUniform3D1() const { std::cout << "Testing extract structured uniform with sampling" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DUniformDataSet1(); @@ -172,7 +172,7 @@ public: void TestRectilinear2D() const { std::cout << "Testing extract structured rectilinear" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DRectilinearDataSet0(); @@ -197,7 +197,7 @@ public: void TestRectilinear3D() const { std::cout << "Testing extract structured rectilinear" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DRectilinearDataSet0(); diff --git a/vtkm/worklet/testing/UnitTestInnerJoin.cxx b/vtkm/worklet/testing/UnitTestInnerJoin.cxx new file mode 100644 index 000000000..5a70fa1dc --- /dev/null +++ b/vtkm/worklet/testing/UnitTestInnerJoin.cxx @@ -0,0 +1,88 @@ +//============================================================================= +// +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2018 UT-Battelle, LLC. +// Copyright 2018 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +// +//============================================================================= + +#include +#include + +template +class TestInnerJoin +{ +public: + template + bool TestArrayHandle(const vtkm::cont::ArrayHandle& ah, + const T* expected, + vtkm::Id size) const + { + if (size != ah.GetNumberOfValues()) + { + return false; + } + + for (vtkm::Id i = 0; i < size; ++i) + { + if (ah.GetPortalConstControl().Get(i) != expected[i]) + { + return false; + } + } + + return true; + } + + void TestTwoArrays() const + { + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; + + std::vector A = { 8, 3, 6, 8, 9, 5, 12, 10, 14 }; + std::vector B = { 7, 11, 9, 8, 5, 1, 0, 5 }; + + vtkm::cont::ArrayHandle A_arr = vtkm::cont::make_ArrayHandle(A); + vtkm::cont::ArrayHandle B_arr = vtkm::cont::make_ArrayHandle(B); + vtkm::cont::ArrayHandle idxA; + vtkm::cont::ArrayHandle idxB; + + Algorithm::Copy(vtkm::cont::ArrayHandleIndex(A_arr.GetNumberOfValues()), idxA); + Algorithm::Copy(vtkm::cont::ArrayHandleIndex(B_arr.GetNumberOfValues()), idxB); + + vtkm::cont::ArrayHandle joinedIndex; + vtkm::cont::ArrayHandle outA; + vtkm::cont::ArrayHandle outB; + + InnerJoin().Run(A_arr, idxA, B_arr, idxB, joinedIndex, outA, outB); + + vtkm::Id expectedIndex[] = { 5, 5, 8, 8, 9 }; + VTKM_TEST_ASSERT(TestArrayHandle(joinedIndex, expectedIndex, 5), "Wrong joined keys"); + + vtkm::Id expectedOutA[] = { 5, 5, 0, 3, 4 }; + VTKM_TEST_ASSERT(TestArrayHandle(outA, expectedOutA, 5), "Wrong joined values"); + + vtkm::Id expectedOutB[] = { 4, 7, 3, 3, 2 }; + VTKM_TEST_ASSERT(TestArrayHandle(outB, expectedOutB, 5), "Wrong joined values"); + } + + void operator()() const { this->TestTwoArrays(); } +}; + +int UnitTestInnerJoin(int, char* []) +{ + return vtkm::cont::testing::Testing::Run(TestInnerJoin()); +} diff --git a/vtkm/worklet/testing/UnitTestKdTreeBuildNNS.cxx b/vtkm/worklet/testing/UnitTestKdTreeBuildNNS.cxx index 1945c11bd..fdc95b00d 100644 --- a/vtkm/worklet/testing/UnitTestKdTreeBuildNNS.cxx +++ b/vtkm/worklet/testing/UnitTestKdTreeBuildNNS.cxx @@ -24,7 +24,7 @@ namespace { -typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; +using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; ////brute force method ///// template diff --git a/vtkm/worklet/testing/UnitTestMagnitude.cxx b/vtkm/worklet/testing/UnitTestMagnitude.cxx index d13462b16..da36d6486 100644 --- a/vtkm/worklet/testing/UnitTestMagnitude.cxx +++ b/vtkm/worklet/testing/UnitTestMagnitude.cxx @@ -32,9 +32,9 @@ void TestMagnitude() vtkm::worklet::Magnitude magnitudeWorklet; - typedef vtkm::cont::ArrayHandle ArrayReturnType; - typedef vtkm::cont::ArrayHandle> ArrayVectorType; - typedef ArrayVectorType::PortalControl PortalType; + using ArrayReturnType = vtkm::cont::ArrayHandle; + using ArrayVectorType = vtkm::cont::ArrayHandle>; + using PortalType = ArrayVectorType::PortalControl; ArrayVectorType pythagoreanTriples; pythagoreanTriples.Allocate(5); diff --git a/vtkm/worklet/testing/UnitTestMarchingCubes.cxx b/vtkm/worklet/testing/UnitTestMarchingCubes.cxx index 02457d4d7..9dc010730 100644 --- a/vtkm/worklet/testing/UnitTestMarchingCubes.cxx +++ b/vtkm/worklet/testing/UnitTestMarchingCubes.cxx @@ -36,7 +36,7 @@ class TangleField : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn vertexId, FieldOut v); typedef void ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; const vtkm::Id xdim, ydim, zdim; const vtkm::FloatDefault xmin, ymin, zmin, xmax, ymax, zmax; @@ -169,8 +169,8 @@ public: VTKM_EXEC_CONT vtkm::Id operator()(vtkm::Id vertex) const { - typedef vtkm::CellShapeTagHexahedron HexTag; - typedef vtkm::CellTraits HexTraits; + using HexTag = vtkm::CellShapeTagHexahedron; + using HexTraits = vtkm::CellTraits; vtkm::Id cellId = vertex / HexTraits::NUM_POINTS; vtkm::Id localId = vertex % HexTraits::NUM_POINTS; @@ -210,18 +210,16 @@ private: class MakeRadiantDataSet { public: - typedef vtkm::cont::ArrayHandleUniformPointCoordinates CoordinateArrayHandle; - typedef vtkm::cont::ArrayHandleTransform - DataArrayHandle; - typedef vtkm::cont::ArrayHandleTransform, - CubeGridConnectivity> - ConnectivityArrayHandle; - - typedef vtkm::cont::CellSetSingleType< + using CoordinateArrayHandle = vtkm::cont::ArrayHandleUniformPointCoordinates; + using DataArrayHandle = + vtkm::cont::ArrayHandleTransform; + using ConnectivityArrayHandle = vtkm::cont::ArrayHandleTransform, - CubeGridConnectivity>::StorageTag> - CellSet; + CubeGridConnectivity>; + + using CellSet = vtkm::cont::CellSetSingleType< + vtkm::cont::ArrayHandleTransform, + CubeGridConnectivity>::StorageTag>; vtkm::cont::DataSet Make3DRadiantDataSet(vtkm::IdComponent dim = 5); }; @@ -233,10 +231,10 @@ inline vtkm::cont::DataSet MakeRadiantDataSet::Make3DRadiantDataSet(vtkm::IdComp vtkm::cont::DataSet dataSet; - typedef vtkm::CellShapeTagHexahedron HexTag; - typedef vtkm::CellTraits HexTraits; + using HexTag = vtkm::CellShapeTagHexahedron; + using HexTraits = vtkm::CellTraits; - typedef vtkm::Vec CoordType; + using CoordType = vtkm::Vec; const vtkm::IdComponent nCells = dim * dim * dim; @@ -284,7 +282,7 @@ void TestMarchingCubesUniformGrid() vtkm::Id3 dims(4, 4, 4); vtkm::cont::DataSet dataSet = MakeIsosurfaceTestDataSet(dims); - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; vtkm::cont::CellSetStructured<3> cellSet; dataSet.GetCellSet().CopyTo(cellSet); vtkm::cont::ArrayHandle pointFieldArray; @@ -338,10 +336,10 @@ void TestMarchingCubesExplicit() { std::cout << "Testing MarchingCubes filter on explicit data" << std::endl; - typedef MakeRadiantDataSet DataSetGenerator; - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef vtkm::cont::ArrayHandle> Vec3Handle; - typedef vtkm::cont::ArrayHandle DataHandle; + using DataSetGenerator = MakeRadiantDataSet; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using Vec3Handle = vtkm::cont::ArrayHandle>; + using DataHandle = vtkm::cont::ArrayHandle; DataSetGenerator dataSetGenerator; diff --git a/vtkm/worklet/testing/UnitTestMask.cxx b/vtkm/worklet/testing/UnitTestMask.cxx index 86af74620..ef7ad3d48 100644 --- a/vtkm/worklet/testing/UnitTestMask.cxx +++ b/vtkm/worklet/testing/UnitTestMask.cxx @@ -41,8 +41,8 @@ public: { std::cout << "Testing mask cells structured:" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make2DUniformDataSet1(); @@ -69,8 +69,8 @@ public: { std::cout << "Testing mask cells structured:" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); CellSetType cellSet; @@ -96,8 +96,8 @@ public: { std::cout << "Testing mask cells explicit:" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; + using OutCellSetType = vtkm::cont::CellSetPermutation; // Input data set created vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); diff --git a/vtkm/worklet/testing/UnitTestMaskPoints.cxx b/vtkm/worklet/testing/UnitTestMaskPoints.cxx index f564d6d95..9fab6cdf4 100644 --- a/vtkm/worklet/testing/UnitTestMaskPoints.cxx +++ b/vtkm/worklet/testing/UnitTestMaskPoints.cxx @@ -43,7 +43,7 @@ public: { std::cout << "Testing mask points stride on 2D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make2DUniformDataSet1(); @@ -64,7 +64,7 @@ public: { std::cout << "Testing mask points stride on 3D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -85,7 +85,7 @@ public: { std::cout << "Testing mask points stride on 3D explicit dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); diff --git a/vtkm/worklet/testing/UnitTestNDimsHistMarginalization.cxx b/vtkm/worklet/testing/UnitTestNDimsHistMarginalization.cxx index 3417a4425..a1c45e844 100644 --- a/vtkm/worklet/testing/UnitTestNDimsHistMarginalization.cxx +++ b/vtkm/worklet/testing/UnitTestNDimsHistMarginalization.cxx @@ -192,7 +192,7 @@ vtkm::cont::DataSet MakeTestDataSet() // marginal histogram // In this example, we have three variable var0, var1, var2 // the condition is P(Var0, Var2 | 1& vec, vtkm::cont::ArrayHandle>& vecField) { - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef typename vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using DeviceAlgorithm = typename vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::ArrayHandleConstant> vecConst; vecConst = vtkm::cont::make_ArrayHandleConstant(vec, num); @@ -199,9 +199,9 @@ void ValidateEvaluator(const EvalType& eval, const vtkm::Vec& vec, const std::string& msg) { - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef TestEvaluatorWorklet EvalTester; - typedef vtkm::worklet::DispatcherMapField EvalTesterDispatcher; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using EvalTester = TestEvaluatorWorklet; + using EvalTesterDispatcher = vtkm::worklet::DispatcherMapField; EvalTester evalTester(eval); EvalTesterDispatcher evalTesterDispatcher(evalTester); vtkm::cont::ArrayHandle> pointsHandle = @@ -257,10 +257,10 @@ void ValidateIntegrator(const IntegratorType& integrator, const std::vector>& expStepResults, const std::string& msg) { - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef TestIntegratorWorklet IntegratorTester; - typedef vtkm::worklet::DispatcherMapField IntegratorTesterDispatcher; - typedef vtkm::worklet::particleadvection::ParticleStatus Status; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using IntegratorTester = TestIntegratorWorklet; + using IntegratorTesterDispatcher = vtkm::worklet::DispatcherMapField; + using Status = vtkm::worklet::particleadvection::ParticleStatus; IntegratorTester integratorTester(integrator); IntegratorTesterDispatcher integratorTesterDispatcher(integratorTester); vtkm::cont::ArrayHandle> pointsHandle = @@ -291,30 +291,30 @@ void ValidateIntegrator(const IntegratorType& integrator, void TestEvaluators() { - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef vtkm::Float32 FieldType; - typedef vtkm::cont::ArrayHandle> FieldHandle; - typedef FieldHandle::template ExecutionTypes::PortalConst FieldPortalConstType; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using FieldType = vtkm::Float32; + using FieldHandle = vtkm::cont::ArrayHandle>; + using FieldPortalConstType = FieldHandle::template ExecutionTypes::PortalConst; //Constant field evaluator and RK4 integrator. - typedef vtkm::worklet::particleadvection::ConstantField CEvalType; - typedef vtkm::worklet::particleadvection::RK4Integrator RK4CType; + using CEvalType = vtkm::worklet::particleadvection::ConstantField; + using RK4CType = vtkm::worklet::particleadvection::RK4Integrator; //Uniform grid evaluator and RK4 integrator. - typedef vtkm::worklet::particleadvection::UniformGridEvaluate - UniformEvalType; - typedef vtkm::worklet::particleadvection::RK4Integrator - RK4UniformType; + using UniformEvalType = + vtkm::worklet::particleadvection::UniformGridEvaluate; + using RK4UniformType = + vtkm::worklet::particleadvection::RK4Integrator; //Rectilinear grid evaluator and RK4 integrator. - typedef vtkm::worklet::particleadvection::RectilinearGridEvaluate - RectilinearEvalType; - typedef vtkm::worklet::particleadvection::RK4Integrator - RK4RectilinearType; + using RectilinearEvalType = + vtkm::worklet::particleadvection::RectilinearGridEvaluate; + using RK4RectilinearType = + vtkm::worklet::particleadvection::RK4Integrator; std::vector> vecs; vecs.push_back(vtkm::Vec(1, 0, 0)); @@ -410,10 +410,10 @@ void TestEvaluators() void TestParticleWorklets() { - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; - typedef vtkm::Float32 FieldType; - typedef vtkm::cont::ArrayHandle> FieldHandle; - typedef FieldHandle::template ExecutionTypes::PortalConst FieldPortalConstType; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + using FieldType = vtkm::Float32; + using FieldHandle = vtkm::cont::ArrayHandle>; + using FieldPortalConstType = FieldHandle::template ExecutionTypes::PortalConst; FieldType stepSize = 0.05f; @@ -433,11 +433,10 @@ void TestParticleWorklets() } vtkm::cont::DataSet ds = dataSetBuilder.Create(dims); - typedef vtkm::worklet::particleadvection::UniformGridEvaluate - RGEvalType; - typedef vtkm::worklet::particleadvection::RK4Integrator RK4RGType; + using RGEvalType = vtkm::worklet::particleadvection::UniformGridEvaluate; + using RK4RGType = vtkm::worklet::particleadvection::RK4Integrator; vtkm::cont::ArrayHandle> fieldArray; fieldArray = vtkm::cont::make_ArrayHandle(field); diff --git a/vtkm/worklet/testing/UnitTestProbe.cxx b/vtkm/worklet/testing/UnitTestProbe.cxx new file mode 100644 index 000000000..4c59f5bd3 --- /dev/null +++ b/vtkm/worklet/testing/UnitTestProbe.cxx @@ -0,0 +1,235 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ +#include + +#include +#include +#include +#include + +#include + +namespace +{ + +vtkm::cont::DataSet MakeInputDataSet() +{ + auto input = vtkm::cont::DataSetBuilderUniform::Create( + vtkm::Id2(4, 4), vtkm::make_Vec(0.0f, 0.0f), vtkm::make_Vec(1.0f, 1.0f)); + vtkm::cont::DataSetFieldAdd::AddPointField( + input, "pointdata", vtkm::cont::make_ArrayHandleCounting(0.0f, 0.3f, 16)); + vtkm::cont::DataSetFieldAdd::AddCellField( + input, "celldata", vtkm::cont::make_ArrayHandleCounting(0.0f, 0.7f, 9)); + return input; +} + +vtkm::cont::DataSet MakeGeometryDataSet() +{ + auto geometry = vtkm::cont::DataSetBuilderUniform::Create( + vtkm::Id2(9, 9), vtkm::make_Vec(0.7f, 0.7f), vtkm::make_Vec(0.35f, 0.35f)); + return geometry; +} + +template +vtkm::cont::DataSet ConvertDataSetUniformToExplicit(const vtkm::cont::DataSet& uds, + DeviceAdapter device) +{ + vtkm::cont::DataSet eds; + + vtkm::cont::CellSetExplicit<> cs(uds.GetCellSet().GetName()); + vtkm::worklet::CellDeepCopy::Run(uds.GetCellSet(), cs, device); + eds.AddCellSet(cs); + + vtkm::cont::ArrayHandle> points; + vtkm::cont::DeviceAdapterAlgorithm::Copy(uds.GetCoordinateSystem().GetData(), + points); + eds.AddCoordinateSystem( + vtkm::cont::CoordinateSystem(uds.GetCoordinateSystem().GetName(), points)); + + for (vtkm::IdComponent i = 0; i < uds.GetNumberOfFields(); ++i) + { + eds.AddField(uds.GetField(i)); + } + + return eds; +} + +const std::vector& GetExpectedPointData() +{ + static std::vector expected = { + 1.05f, 1.155f, 1.26f, 1.365f, 1.47f, 1.575f, 1.68f, 0.0f, 0.0f, 1.47f, 1.575f, 1.68f, + 1.785f, 1.89f, 1.995f, 2.1f, 0.0f, 0.0f, 1.89f, 1.995f, 2.1f, 2.205f, 2.31f, 2.415f, + 2.52f, 0.0f, 0.0f, 2.31f, 2.415f, 2.52f, 2.625f, 2.73f, 2.835f, 2.94f, 0.0f, 0.0f, + 2.73f, 2.835f, 2.94f, 3.045f, 3.15f, 3.255f, 3.36f, 0.0f, 0.0f, 3.15f, 3.255f, 3.36f, + 3.465f, 3.57f, 3.675f, 3.78f, 0.0f, 0.0f, 3.57f, 3.675f, 3.78f, 3.885f, 3.99f, 4.095f, + 4.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + return expected; +} + +const std::vector& GetExpectedCellData() +{ + static std::vector expected = { + 0.0f, 0.7f, 0.7f, 0.7f, 1.4f, 1.4f, 1.4f, 0.0f, 0.0f, 2.1f, 2.8f, 2.8f, 2.8f, 3.5f, + 3.5f, 3.5f, 0.0f, 0.0f, 2.1f, 2.8f, 2.8f, 2.8f, 3.5f, 3.5f, 3.5f, 0.0f, 0.0f, 2.1f, + 2.8f, 2.8f, 2.8f, 3.5f, 3.5f, 3.5f, 0.0f, 0.0f, 4.2f, 4.9f, 4.9f, 4.9f, 5.6f, 5.6f, + 5.6f, 0.0f, 0.0f, 4.2f, 4.9f, 4.9f, 4.9f, 5.6f, 5.6f, 5.6f, 0.0f, 0.0f, 4.2f, 4.9f, + 4.9f, 4.9f, 5.6f, 5.6f, 5.6f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f + }; + return expected; +} + +const std::vector& GetExpectedHiddenPoints() +{ + static std::vector expected = { 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, + 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, + 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, + 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; + return expected; +} + +const std::vector& GetExpectedHiddenCells() +{ + static std::vector expected = { 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }; + return expected; +} + +template +void TestResultArray(const vtkm::cont::ArrayHandle& result, const std::vector& expected) +{ + VTKM_TEST_ASSERT(result.GetNumberOfValues() == static_cast(expected.size()), + "Incorrect field size"); + + auto portal = result.GetPortalConstControl(); + vtkm::Id size = portal.GetNumberOfValues(); + for (vtkm::Id i = 0; i < size; ++i) + { + VTKM_TEST_ASSERT(test_equal(portal.Get(i), expected[static_cast(i)]), + "Incorrect field value"); + } +} + +template +class TestProbe +{ +private: + using FieldArrayType = vtkm::cont::ArrayHandleCounting; + + static void ExplicitToUnifrom() + { + std::cout << "Testing Probe Explicit to Uniform:\n"; + + auto input = ConvertDataSetUniformToExplicit(MakeInputDataSet(), DeviceAdapter()); + auto geometry = MakeGeometryDataSet(); + + vtkm::worklet::Probe probe; + probe.Run(input.GetCellSet(), + input.GetCoordinateSystem(), + geometry.GetCoordinateSystem(), + DeviceAdapter()); + + auto pf = probe.ProcessPointField( + input.GetField("pointdata").GetData().template Cast(), DeviceAdapter()); + auto cf = probe.ProcessCellField( + input.GetField("celldata").GetData().template Cast(), DeviceAdapter()); + auto hp = probe.GetHiddenPointsField(DeviceAdapter()); + auto hc = probe.GetHiddenCellsField(geometry.GetCellSet(), DeviceAdapter()); + + TestResultArray(pf, GetExpectedPointData()); + TestResultArray(cf, GetExpectedCellData()); + TestResultArray(hp, GetExpectedHiddenPoints()); + TestResultArray(hc, GetExpectedHiddenCells()); + } + + static void UniformToExplict() + { + std::cout << "Testing Probe Uniform to Explicit:\n"; + + auto input = MakeInputDataSet(); + auto geometry = ConvertDataSetUniformToExplicit(MakeGeometryDataSet(), DeviceAdapter()); + + vtkm::worklet::Probe probe; + probe.Run(input.GetCellSet(), + input.GetCoordinateSystem(), + geometry.GetCoordinateSystem(), + DeviceAdapter()); + + auto pf = probe.ProcessPointField( + input.GetField("pointdata").GetData().template Cast(), DeviceAdapter()); + auto cf = probe.ProcessCellField( + input.GetField("celldata").GetData().template Cast(), DeviceAdapter()); + + auto hp = probe.GetHiddenPointsField(DeviceAdapter()); + auto hc = probe.GetHiddenCellsField(geometry.GetCellSet(), DeviceAdapter()); + + TestResultArray(pf, GetExpectedPointData()); + TestResultArray(cf, GetExpectedCellData()); + TestResultArray(hp, GetExpectedHiddenPoints()); + TestResultArray(hc, GetExpectedHiddenCells()); + } + + static void ExplicitToExplict() + { + std::cout << "Testing Probe Explicit to Explicit:\n"; + + auto input = ConvertDataSetUniformToExplicit(MakeInputDataSet(), DeviceAdapter()); + auto geometry = ConvertDataSetUniformToExplicit(MakeGeometryDataSet(), DeviceAdapter()); + + vtkm::worklet::Probe probe; + probe.Run(input.GetCellSet(), + input.GetCoordinateSystem(), + geometry.GetCoordinateSystem(), + DeviceAdapter()); + + auto pf = probe.ProcessPointField( + input.GetField("pointdata").GetData().template Cast(), DeviceAdapter()); + auto cf = probe.ProcessCellField( + input.GetField("celldata").GetData().template Cast(), DeviceAdapter()); + + auto hp = probe.GetHiddenPointsField(DeviceAdapter()); + auto hc = probe.GetHiddenCellsField(geometry.GetCellSet(), DeviceAdapter()); + + TestResultArray(pf, GetExpectedPointData()); + TestResultArray(cf, GetExpectedCellData()); + TestResultArray(hp, GetExpectedHiddenPoints()); + TestResultArray(hc, GetExpectedHiddenCells()); + } + +public: + static void Run() + { + ExplicitToUnifrom(); + UniformToExplict(); + ExplicitToExplict(); + } +}; + +} // anonymous namespace + +int UnitTestProbe(int, char* []) +{ + return vtkm::cont::testing::Testing::Run(TestProbe::Run); +} diff --git a/vtkm/worklet/testing/UnitTestScalarsToColors.cxx b/vtkm/worklet/testing/UnitTestScalarsToColors.cxx new file mode 100644 index 000000000..191eedd13 --- /dev/null +++ b/vtkm/worklet/testing/UnitTestScalarsToColors.cxx @@ -0,0 +1,411 @@ +//============================================================================ +// Copyright (c) Kitware, Inc. +// All rights reserved. +// See LICENSE.txt for details. +// This software is distributed WITHOUT ANY WARRANTY; without even +// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the above copyright notice for more information. +// +// Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). +// Copyright 2014 UT-Battelle, LLC. +// Copyright 2014 Los Alamos National Security. +// +// Under the terms of Contract DE-NA0003525 with NTESS, +// the U.S. Government retains certain rights in this software. +// +// Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National +// Laboratory (LANL), the U.S. Government retains certain rights in +// this software. +//============================================================================ + +#include +#include + +namespace +{ + +// data we want are valid values between 0 and 1 that represent the fraction +// of the range we want to map into. +std::vector test_values = { 0.0f, 0.125f, 0.25f, 0.5f, 0.625, 0.75f, 1.0f }; +std::vector> rgb_result = { + { 0, 0, 0 }, { 32, 32, 32 }, { 64, 64, 64 }, { 128, 128, 128 }, + { 159, 159, 159 }, { 191, 191, 191 }, { 255, 255, 255 }, +}; + +template +T as_color(vtkm::Float32 v, vtkm::Float32) +{ + return static_cast(v); +} + +template <> +vtkm::UInt8 as_color(vtkm::Float32 v, vtkm::Float32) +{ + return static_cast(v * 255.0f + 0.5f); +} + +template <> +vtkm::Vec as_color>(vtkm::Float32 v, + vtkm::Float32 alpha) +{ //generate luminance+alpha values + return vtkm::Vec(v, alpha); +} +template <> +vtkm::Vec as_color>(vtkm::Float32 v, + vtkm::Float32 alpha) +{ //generate luminance+alpha values + return vtkm::Vec(v, alpha); +} +template <> +vtkm::Vec as_color>(vtkm::Float32 v, vtkm::Float32 alpha) +{ //generate luminance+alpha values + return vtkm::Vec(static_cast(v * 255.0f + 0.5f), + static_cast(alpha * 255.0f + 0.5f)); +} + +template <> +vtkm::Vec as_color>(vtkm::Float32 v, vtkm::Float32) +{ //vec 3 are always rgb + return vtkm::Vec(static_cast(v * 255.0f + 0.5f)); +} + +template <> +vtkm::Vec as_color>(vtkm::Float32 v, + vtkm::Float32 alpha) +{ //generate rgba + return vtkm::Vec(v, v, v, alpha); +} +template <> +vtkm::Vec as_color>(vtkm::Float32 v, + vtkm::Float32 alpha) +{ //generate rgba + return vtkm::Vec(v, v, v, alpha); +} +template <> +vtkm::Vec as_color>(vtkm::Float32 v, vtkm::Float32 alpha) +{ //generate rgba + return vtkm::Vec(static_cast(v * 255.0f + 0.5f), + static_cast(v * 255.0f + 0.5f), + static_cast(v * 255.0f + 0.5f), + static_cast(alpha * 255.0f + 0.5f)); +} + + +template +vtkm::cont::ArrayHandle make_data(const vtkm::Range& r) +{ + using BaseT = typename vtkm::BaseComponent::Type; + vtkm::Float32 shift, scale; + vtkm::worklet::colorconversion::ComputeShiftScale(r, shift, scale); + const bool shiftscale = vtkm::worklet::colorconversion::needShiftScale(BaseT{}, shift, scale); + + + + vtkm::cont::ArrayHandle handle; + handle.Allocate(static_cast(test_values.size())); + + auto portal = handle.GetPortalControl(); + vtkm::Id index = 0; + if (shiftscale) + { + const vtkm::Float32 alpha = static_cast(r.Max); + for (const auto& i : test_values) + { + //we want to apply the shift and scale, and than clamp to the allowed + //range of the data. The problem is that we might need to shift and scale the alpha value + //for the color + // + const float c = (i * static_cast(r.Length())) - shift; + portal.Set(index++, as_color(c, alpha)); + } + } + else + { + const vtkm::Float32 alpha = 1.0f; + //no shift or scale required + for (const auto& i : test_values) + { + portal.Set(index++, as_color(i, alpha)); + } + } + return handle; +} + +bool verify(vtkm::cont::ArrayHandle> output) +{ + auto portal = output.GetPortalConstControl(); + vtkm::Id index = 0; + for (auto i : rgb_result) + { + auto v = portal.Get(index); + if (v != i) + { + std::cerr << "failed comparison at index: " << index + << " found: " << static_cast>(v) + << " was expecting: " << static_cast>(i) << std::endl; + break; + } + index++; + } + bool valid = static_cast(index) == rgb_result.size(); + return valid; +} + +bool verify(vtkm::Float32 alpha, vtkm::cont::ArrayHandle> output) +{ + const vtkm::UInt8 a = vtkm::worklet::colorconversion::ColorToUChar(alpha); + auto portal = output.GetPortalConstControl(); + vtkm::Id index = 0; + for (auto i : rgb_result) + { + auto v = portal.Get(index); + auto e = vtkm::make_Vec(i[0], i[1], i[2], a); + if (v != e) + { + std::cerr << "failed comparison at index: " << index + << " found: " << static_cast>(v) + << " was expecting: " << static_cast>(e) << std::endl; + break; + } + index++; + } + bool valid = static_cast(index) == rgb_result.size(); + return valid; +} + +#if defined(VTKM_MSVC) +#pragma warning(push) +#pragma warning(disable : 4127) // conditional expression is constant +#endif + +struct TestToRGB +{ + vtkm::worklet::ScalarsToColors Worklet; + + TestToRGB() + : Worklet() + { + } + + TestToRGB(vtkm::Float32 minR, vtkm::Float32 maxR) + : Worklet(vtkm::Range(minR, maxR)) + { + } + + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + template + VTKM_CONT void operator()(T) const + { + //use each component to generate the output + vtkm::cont::ArrayHandle> output; + this->Worklet.Run(make_data(this->Worklet.GetRange()), output, DeviceAdapter()); + bool valid = verify(output); + VTKM_TEST_ASSERT(valid, "scalar RGB failed"); + } + + template + VTKM_CONT void operator()(vtkm::Vec) const + { + bool valid = false; + using T = vtkm::Vec; + + auto input = make_data(this->Worklet.GetRange()); + vtkm::cont::ArrayHandle> output; + + //use all components to generate the output + this->Worklet.Run(input, output, DeviceAdapter()); + valid = verify(output); + VTKM_TEST_ASSERT(valid, "all components RGB failed"); + + //use the magnitude of the vector if vector is 3 components + if (N == 3) + { + //compute the range needed for the magnitude, since the range can span + //negative/positive space we need to find the magnitude of each value + //and them to the range to get the correct range + vtkm::worklet::colorconversion::MagnitudePortal wrapper; + vtkm::Range magr; + auto portal = input.GetPortalControl(); + for (vtkm::Id i = 0; i < input.GetNumberOfValues(); ++i) + { + const auto magv = wrapper(portal.Get(i)); + magr.Include(static_cast(magv)); + } + + vtkm::worklet::ScalarsToColors magWorklet(magr); + magWorklet.RunMagnitude(input, output, DeviceAdapter()); + // vtkm::cont::printSummary_ArrayHandle(output, std::cout, true); + + auto portal2 = output.GetPortalControl(); + for (vtkm::Id i = 0; i < input.GetNumberOfValues(); ++i) + { + const auto expected = wrapper(portal.Get(i)); + const auto percent = (portal2.Get(i)[0] / 255.0f); + const auto result = (percent * magr.Length()) + magr.Min; + if (!test_equal(expected, result, 0.005)) + { + std::cerr << "failed comparison at index: " << i << " found: " << result + << " was expecting: " << expected << std::endl; + VTKM_TEST_ASSERT(test_equal(expected, result), "magnitude RGB failed"); + } + } + } + + //use the components of the vector, if the vector is 2 or 4 we need + //to ignore the last component as it is alpha + int end = (N % 2 == 0) ? (N - 1) : N; + for (int i = 0; i < end; ++i) + { + this->Worklet.RunComponent(input, i, output, DeviceAdapter()); + valid = verify(output); + VTKM_TEST_ASSERT(valid, "per component RGB failed"); + } + } +}; + +struct TestToRGBA +{ + vtkm::worklet::ScalarsToColors Worklet; + + TestToRGBA() + : Worklet() + { + } + + TestToRGBA(vtkm::Float32 minR, vtkm::Float32 maxR, vtkm::Float32 alpha) + : Worklet(vtkm::Range(minR, maxR), alpha) + { + } + + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; + template + VTKM_CONT void operator()(T) const + { + //use each component to generate the output + vtkm::cont::ArrayHandle> output; + this->Worklet.Run(make_data(this->Worklet.GetRange()), output, DeviceAdapter()); + + bool valid = verify(this->Worklet.GetAlpha(), output); + VTKM_TEST_ASSERT(valid, "scalar RGBA failed"); + } + + template + VTKM_CONT void operator()(vtkm::Vec) const + { + bool valid = false; + using T = vtkm::Vec; + vtkm::cont::ArrayHandle> output; + + auto input = make_data(this->Worklet.GetRange()); + // vtkm::cont::printSummary_ArrayHandle(input, std::cout, true); + + //use all components to generate the output + this->Worklet.Run(input, output, DeviceAdapter()); + valid = verify(this->Worklet.GetAlpha(), output); + VTKM_TEST_ASSERT(valid, "all components RGBA failed"); + + //use the magnitude of the vector if vector is 3 components + if (N == 3) + { + //compute the range needed for the magnitude, since the range can span + //negative/positive space we need to find the magnitude of each value + //and them to the range to get the correct range + vtkm::worklet::colorconversion::MagnitudePortal wrapper; + vtkm::Range magr; + auto portal = input.GetPortalControl(); + for (vtkm::Id i = 0; i < input.GetNumberOfValues(); ++i) + { + const auto magv = wrapper(portal.Get(i)); + magr.Include(static_cast(magv)); + } + + vtkm::worklet::ScalarsToColors magWorklet(magr); + magWorklet.RunMagnitude(input, output, DeviceAdapter()); + // vtkm::cont::printSummary_ArrayHandle(output, std::cout, true); + + auto portal2 = output.GetPortalControl(); + for (vtkm::Id i = 0; i < input.GetNumberOfValues(); ++i) + { + const auto expected = wrapper(portal.Get(i)); + const auto percent = (portal2.Get(i)[0] / 255.0f); + const auto result = (percent * magr.Length()) + magr.Min; + if (!test_equal(expected, result, 0.005)) + { + std::cerr << "failed comparison at index: " << i << " found: " << result + << " was expecting: " << expected << std::endl; + VTKM_TEST_ASSERT(test_equal(expected, result), "magnitude RGB failed"); + } + } + } + + //use the components of the vector, if the vector is 2 or 4 we need + //to ignore the last component as it is alpha + int end = (N % 2 == 0) ? (N - 1) : N; + for (int i = 0; i < end; ++i) + { + this->Worklet.RunComponent(input, i, output, DeviceAdapter()); + valid = verify(this->Worklet.GetAlpha(), output); + VTKM_TEST_ASSERT(valid, "per component RGB failed"); + } + } +}; + +#if defined(VTKM_MSVC) +#pragma warning(pop) +#endif + + +struct TypeListTagScalarColorTypes : vtkm::ListTagBase, + vtkm::Vec, + vtkm::Vec, + vtkm::Vec, + vtkm::Vec, + vtkm::Vec> +{ +}; + +struct TypeListTagUIntColorTypes : vtkm::ListTagBase, + vtkm::Vec, + vtkm::Vec> +{ +}; + + +void TestScalarsToColors() +{ + std::cout << "Test ConvertToRGB with UInt8 types" << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGB(), TypeListTagUIntColorTypes()); + std::cout << "Test ConvertToRGB with Scalar types" << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGB(0.0f, 1.0f), TypeListTagScalarColorTypes()); + std::cout << "Test ShiftScaleToRGB with scalar types and varying range" << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGB(1024.0f, 4096.0f), TypeListTagScalarColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGB(-2048.0f, 1024.0f), TypeListTagScalarColorTypes()); + + std::cout << "Test ConvertToRGBA with UInt8 types and alpha values=[1.0, 0.5, 0.0]" << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGBA(), TypeListTagUIntColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 255.0f, 0.5f), TypeListTagUIntColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 255.0f, 0.0f), TypeListTagUIntColorTypes()); + + std::cout << "Test ConvertToRGBA with Scalar types and alpha values=[0.3, 0.6, 1.0]" << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 1.0f, 0.3f), TypeListTagScalarColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 1.0f, 0.6f), TypeListTagScalarColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 1.0f, 1.0f), TypeListTagScalarColorTypes()); + + std::cout + << "Test ConvertToRGBA with Scalar types and varying range with alpha values=[0.25, 0.5, 0.75]" + << std::endl; + vtkm::testing::Testing::TryTypes(TestToRGBA(-0.075f, -0.025f, 0.25f), + TypeListTagScalarColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(0.0f, 2048.0f, 0.5f), TypeListTagScalarColorTypes()); + vtkm::testing::Testing::TryTypes(TestToRGBA(-2048.0f, 2048.0f, 0.75f), + TypeListTagScalarColorTypes()); +} +} + +int UnitTestScalarsToColors(int, char* []) +{ + return vtkm::cont::testing::Testing::Run(TestScalarsToColors); +} diff --git a/vtkm/worklet/testing/UnitTestScatterCounting.cxx b/vtkm/worklet/testing/UnitTestScatterCounting.cxx index 3b0c3b263..e45f749f6 100644 --- a/vtkm/worklet/testing/UnitTestScatterCounting.cxx +++ b/vtkm/worklet/testing/UnitTestScatterCounting.cxx @@ -55,7 +55,7 @@ TestScatterArrays MakeScatterArraysShort() const vtkm::IdComponent visitArray[outputSize] = { 0, 0, 1, 0, 0, 0 }; TestScatterArrays arrays; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; // Need to copy arrays so that the data does not go out of scope. Algorithm::Copy(vtkm::cont::make_ArrayHandle(countArray, countArraySize), arrays.CountArray); @@ -78,7 +78,7 @@ TestScatterArrays MakeScatterArraysLong() const vtkm::IdComponent visitArray[outputSize] = { 0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4 }; TestScatterArrays arrays; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; // Need to copy arrays so that the data does not go out of scope. Algorithm::Copy(vtkm::cont::make_ArrayHandle(countArray, countArraySize), arrays.CountArray); @@ -98,7 +98,7 @@ TestScatterArrays MakeScatterArraysZero() const vtkm::Id inputToOutputMap[countArraySize] = { 0, 0, 0, 0, 0, 0 }; TestScatterArrays arrays; - typedef vtkm::cont::DeviceAdapterAlgorithm Algorithm; + using Algorithm = vtkm::cont::DeviceAdapterAlgorithm; // Need to copy arrays so that the data does not go out of scope. Algorithm::Copy(vtkm::cont::make_ArrayHandle(countArray, countArraySize), arrays.CountArray); @@ -118,7 +118,7 @@ struct TestScatterCountingWorklet : public vtkm::worklet::WorkletMapField FieldOut<> recordWorkId); typedef void ExecutionSignature(_1, _2, _3, _4, VisitIndex, WorkIndex); - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } @@ -161,7 +161,7 @@ private: template void CompareArrays(vtkm::cont::ArrayHandle array1, vtkm::cont::ArrayHandle array2) { - typedef typename vtkm::cont::ArrayHandle::PortalConstControl PortalType; + using PortalType = typename vtkm::cont::ArrayHandle::PortalConstControl; PortalType portal1 = array1.GetPortalConstControl(); PortalType portal2 = array2.GetPortalConstControl(); diff --git a/vtkm/worklet/testing/UnitTestSplatKernels.cxx b/vtkm/worklet/testing/UnitTestSplatKernels.cxx index 769b59ac5..6ee8e5cca 100644 --- a/vtkm/worklet/testing/UnitTestSplatKernels.cxx +++ b/vtkm/worklet/testing/UnitTestSplatKernels.cxx @@ -31,7 +31,7 @@ #include "KernelWendland.h" */ -typedef vtkm::Vec Vector; +using Vector = vtkm::Vec; // Simpson integradion rule double SimpsonIntegration(const std::vector& y, const std::vector& x) diff --git a/vtkm/worklet/testing/UnitTestStreamLineUniformGrid.cxx b/vtkm/worklet/testing/UnitTestStreamLineUniformGrid.cxx index 048eb1f08..eb13a2ec0 100644 --- a/vtkm/worklet/testing/UnitTestStreamLineUniformGrid.cxx +++ b/vtkm/worklet/testing/UnitTestStreamLineUniformGrid.cxx @@ -113,7 +113,7 @@ void TestStreamLineUniformGrid() { std::cout << "Testing StreamLineUniformGrid Filter" << std::endl; - typedef VTKM_DEFAULT_DEVICE_ADAPTER_TAG DeviceAdapter; + using DeviceAdapter = VTKM_DEFAULT_DEVICE_ADAPTER_TAG; // Parameters for streamlines vtkm::Id numSeeds = 5; diff --git a/vtkm/worklet/testing/UnitTestStreamingSine.cxx b/vtkm/worklet/testing/UnitTestStreamingSine.cxx index 1f74450fd..1a30b4e98 100644 --- a/vtkm/worklet/testing/UnitTestStreamingSine.cxx +++ b/vtkm/worklet/testing/UnitTestStreamingSine.cxx @@ -77,7 +77,7 @@ void TestStreamingSine() } input = vtkm::cont::make_ArrayHandle(data); - typedef vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithms; + using DeviceAlgorithms = vtkm::cont::DeviceAdapterAlgorithm; vtkm::worklet::SineWorklet sineWorklet; vtkm::worklet::DispatcherStreamingMapField dispatcher(sineWorklet); dispatcher.SetNumberOfBlocks(NBlocks); diff --git a/vtkm/worklet/testing/UnitTestTetrahedralize.cxx b/vtkm/worklet/testing/UnitTestTetrahedralize.cxx index d3dd4e182..a0c127fa3 100644 --- a/vtkm/worklet/testing/UnitTestTetrahedralize.cxx +++ b/vtkm/worklet/testing/UnitTestTetrahedralize.cxx @@ -40,8 +40,8 @@ public: void TestStructured() const { std::cout << "Testing TetrahedralizeStructured" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DUniformDataSet0(); @@ -68,8 +68,8 @@ public: void TestExplicit() const { std::cout << "Testing TetrahedralizeExplicit" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Create the input explicit cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DExplicitDataSet5(); diff --git a/vtkm/worklet/testing/UnitTestThreshold.cxx b/vtkm/worklet/testing/UnitTestThreshold.cxx index a3cbb72a3..5beba5e5e 100644 --- a/vtkm/worklet/testing/UnitTestThreshold.cxx +++ b/vtkm/worklet/testing/UnitTestThreshold.cxx @@ -61,8 +61,8 @@ public: { std::cout << "Testing threshold on 2D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; + using OutCellSetType = vtkm::cont::CellSetPermutation; vtkm::cont::DataSet dataset = MakeTestDataSet().Make2DUniformDataSet0(); @@ -92,8 +92,8 @@ public: { std::cout << "Testing threshold on 3D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetStructured<3> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<3>; + using OutCellSetType = vtkm::cont::CellSetPermutation; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet0(); @@ -124,8 +124,8 @@ public: { std::cout << "Testing threshold on 3D explicit dataset" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; - typedef vtkm::cont::CellSetPermutation OutCellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; + using OutCellSetType = vtkm::cont::CellSetPermutation; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet0(); diff --git a/vtkm/worklet/testing/UnitTestThresholdPoints.cxx b/vtkm/worklet/testing/UnitTestThresholdPoints.cxx index c02c311e7..ae7d67fa6 100644 --- a/vtkm/worklet/testing/UnitTestThresholdPoints.cxx +++ b/vtkm/worklet/testing/UnitTestThresholdPoints.cxx @@ -106,7 +106,7 @@ public: { std::cout << "Testing threshold on 2D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make2DUniformDataSet1(); @@ -138,7 +138,7 @@ public: { std::cout << "Testing threshold on 3D uniform dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DUniformDataSet1(); @@ -164,7 +164,7 @@ public: { std::cout << "Testing threshold on 3D explicit dataset" << std::endl; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; vtkm::cont::DataSet dataset = MakeTestDataSet().Make3DExplicitDataSet5(); diff --git a/vtkm/worklet/testing/UnitTestTriangulate.cxx b/vtkm/worklet/testing/UnitTestTriangulate.cxx index d2bcfc91e..58d8c04dc 100644 --- a/vtkm/worklet/testing/UnitTestTriangulate.cxx +++ b/vtkm/worklet/testing/UnitTestTriangulate.cxx @@ -35,8 +35,8 @@ public: void TestStructured() const { std::cout << "Testing TriangulateStructured:" << std::endl; - typedef vtkm::cont::CellSetStructured<2> CellSetType; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using CellSetType = vtkm::cont::CellSetStructured<2>; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DUniformDataSet1(); @@ -60,8 +60,8 @@ public: void TestExplicit() const { std::cout << "Testing TriangulateExplicit:" << std::endl; - typedef vtkm::cont::CellSetExplicit<> CellSetType; - typedef vtkm::cont::CellSetSingleType<> OutCellSetType; + using CellSetType = vtkm::cont::CellSetExplicit<>; + using OutCellSetType = vtkm::cont::CellSetSingleType<>; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DExplicitDataSet0(); diff --git a/vtkm/worklet/testing/UnitTestVertexClustering.cxx b/vtkm/worklet/testing/UnitTestVertexClustering.cxx index b8d18fa08..5f6ed89f3 100644 --- a/vtkm/worklet/testing/UnitTestVertexClustering.cxx +++ b/vtkm/worklet/testing/UnitTestVertexClustering.cxx @@ -67,7 +67,7 @@ void TestVertexClustering() vtkm::Float32 output_cellvar[output_pointIds / 3] = { 145.f, 134.f, 138.f, 140.f, 149.f, 144.f }; { - typedef vtkm::cont::CellSetSingleType<> CellSetType; + using CellSetType = vtkm::cont::CellSetSingleType<>; CellSetType cellSet; outDataSet.GetCellSet(0).CopyTo(cellSet); auto cellArray = @@ -89,7 +89,7 @@ void TestVertexClustering() VTKM_TEST_ASSERT(outDataSet.GetNumberOfCoordinateSystems() == 1, "Number of output coordinate systems mismatch"); - typedef vtkm::Vec PointType; + using PointType = vtkm::Vec; auto pointArray = outDataSet.GetCoordinateSystem(0).GetData(); VTKM_TEST_ASSERT(pointArray.GetNumberOfValues() == output_points, "Number of output points mismatch"); @@ -100,7 +100,7 @@ void TestVertexClustering() VTKM_TEST_ASSERT(test_equal(p1, p2), "Point Array mismatch"); } - typedef vtkm::cont::CellSetSingleType<> CellSetType; + using CellSetType = vtkm::cont::CellSetSingleType<>; VTKM_TEST_ASSERT(outDataSet.GetNumberOfCellSets() == 1, "Number of output cellsets mismatch"); CellSetType cellSet; outDataSet.GetCellSet(0).CopyTo(cellSet); diff --git a/vtkm/worklet/testing/UnitTestWaveletCompressor.cxx b/vtkm/worklet/testing/UnitTestWaveletCompressor.cxx index 9c7632eaf..ec166d529 100644 --- a/vtkm/worklet/testing/UnitTestWaveletCompressor.cxx +++ b/vtkm/worklet/testing/UnitTestWaveletCompressor.cxx @@ -152,7 +152,7 @@ private: template void FillArray2D(ArrayType& array, vtkm::Id dimX, vtkm::Id dimY) { - typedef vtkm::worklet::wavelets::GaussianWorklet2D WorkletType; + using WorkletType = vtkm::worklet::wavelets::GaussianWorklet2D; WorkletType worklet(dimX, dimY, 100.0, @@ -166,7 +166,7 @@ void FillArray2D(ArrayType& array, vtkm::Id dimX, vtkm::Id dimY) template void FillArray3D(ArrayType& array, vtkm::Id dimX, vtkm::Id dimY, vtkm::Id dimZ) { - typedef vtkm::worklet::wavelets::GaussianWorklet3D WorkletType; + using WorkletType = vtkm::worklet::wavelets::GaussianWorklet3D; WorkletType worklet(dimX, dimY, dimZ); vtkm::worklet::DispatcherMapField dispatcher(worklet); dispatcher.Invoke(array); diff --git a/vtkm/worklet/testing/UnitTestWorkletMapField.cxx b/vtkm/worklet/testing/UnitTestWorkletMapField.cxx index 970242690..107a8aac9 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapField.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapField.cxx @@ -175,7 +175,7 @@ struct DoTestWorklet void TestWorkletMapField() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Map Field on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletMapFieldExecArg.cxx b/vtkm/worklet/testing/UnitTestWorkletMapFieldExecArg.cxx index 3b35923c6..45c7fba52 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapFieldExecArg.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapFieldExecArg.cxx @@ -104,7 +104,7 @@ struct DoTestWorklet void TestWorkletMapFieldExecArg() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Worklet with WholeArray on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletMapFieldWholeArray.cxx b/vtkm/worklet/testing/UnitTestWorkletMapFieldWholeArray.cxx index 286d2d546..49d9e34e5 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapFieldWholeArray.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapFieldWholeArray.cxx @@ -38,20 +38,20 @@ public: const InOutPortalType& inOutPortal, const OutPortalType& outPortal) const { - typedef typename InPortalType::ValueType inT; + using inT = typename InPortalType::ValueType; if (!test_equal(inPortal.Get(index), TestValue(index, inT()))) { this->RaiseError("Got wrong input value."); } - typedef typename InOutPortalType::ValueType inOutT; + using inOutT = typename InOutPortalType::ValueType; if (!test_equal(inOutPortal.Get(index), TestValue(index, inOutT()) + inOutT(100))) { this->RaiseError("Got wrong input/output value."); } inOutPortal.Set(index, TestValue(index, inOutT())); - typedef typename OutPortalType::ValueType outT; + using outT = typename OutPortalType::ValueType; outPortal.Set(index, TestValue(index, outT())); } }; @@ -61,12 +61,12 @@ class TestAtomicArrayWorklet : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn<>, AtomicArrayInOut<>); typedef void ExecutionSignature(WorkIndex, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC void operator()(const vtkm::Id& index, const AtomicArrayType& atomicArray) const { - typedef typename AtomicArrayType::ValueType ValueType; + using ValueType = typename AtomicArrayType::ValueType; atomicArray.Add(0, static_cast(index)); } }; @@ -78,7 +78,7 @@ static const vtkm::Id ARRAY_SIZE = 10; struct DoTestWholeArrayWorklet { - typedef TestWholeArrayWorklet WorkletType; + using WorkletType = TestWholeArrayWorklet; // This just demonstrates that the WholeArray tags support dynamic arrays. VTKM_CONT @@ -122,7 +122,7 @@ struct DoTestWholeArrayWorklet struct DoTestAtomicArrayWorklet { - typedef TestAtomicArrayWorklet WorkletType; + using WorkletType = TestAtomicArrayWorklet; // This just demonstrates that the WholeArray tags support dynamic arrays. VTKM_CONT @@ -153,7 +153,7 @@ struct DoTestAtomicArrayWorklet void TestWorkletMapFieldExecArg() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Worklet with WholeArray on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletMapPointNeighborhood.cxx b/vtkm/worklet/testing/UnitTestWorkletMapPointNeighborhood.cxx index 9810c0fe2..489708676 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapPointNeighborhood.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapPointNeighborhood.cxx @@ -44,7 +44,7 @@ struct MaxNeighborValue : public vtkm::worklet::WorkletPointNeighborhood3x3x3 typedef void ExecutionSignature(OnBoundary, _1, _3); //verify input domain can be something other than first parameter - typedef _2 InputDomain; + using InputDomain = _2; template VTKM_EXEC void operator()(const vtkm::exec::arg::BoundaryState& boundary, @@ -210,7 +210,7 @@ static void TestScatterUnfiormNeighbor(); void TestWorkletPointNeighborhood() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Point Neighborhood Worklet on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletMapTopologyExplicit.cxx b/vtkm/worklet/testing/UnitTestWorkletMapTopologyExplicit.cxx index 2fe43836c..6cfd1a682 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapTopologyExplicit.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapTopologyExplicit.cxx @@ -42,7 +42,7 @@ public: CellSetIn topology, FieldOutCell outCells); typedef void ExecutionSignature(_1, _4, _2, PointCount, CellShape, PointIndices); - typedef _3 InputDomain; + using InputDomain = _3; VTKM_CONT MaxPointOrCellValue() {} @@ -78,7 +78,7 @@ static void TestAvgCellToPoint(); void TestWorkletMapTopologyExplicit() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Topology Worklet ( Explicit ) on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletMapTopologyUniform.cxx b/vtkm/worklet/testing/UnitTestWorkletMapTopologyUniform.cxx index f3da0be35..7d88d583d 100644 --- a/vtkm/worklet/testing/UnitTestWorkletMapTopologyUniform.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletMapTopologyUniform.cxx @@ -42,7 +42,7 @@ public: CellSetIn topology, FieldOutCell outCells); typedef void ExecutionSignature(_1, _4, _2, PointCount, CellShape, PointIndices); - typedef _3 InputDomain; + using InputDomain = _3; VTKM_CONT MaxPointOrCellValue() {} @@ -101,7 +101,7 @@ static void TestStructuredUniformPointCoords(); void TestWorkletMapTopologyUniform() { - typedef vtkm::cont::DeviceAdapterTraits DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Topology Worklet ( Uniform ) on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/testing/UnitTestWorkletReduceByKey.cxx b/vtkm/worklet/testing/UnitTestWorkletReduceByKey.cxx index 25b624fda..bac8b5eb3 100644 --- a/vtkm/worklet/testing/UnitTestWorkletReduceByKey.cxx +++ b/vtkm/worklet/testing/UnitTestWorkletReduceByKey.cxx @@ -57,7 +57,7 @@ struct CheckKeyValuesWorklet : vtkm::worklet::WorkletReduceByKey ValuesInOut<> valuesToModify, ValuesOut<> writeKey); typedef void ExecutionSignature(_1, _2, _3, _4, _5, WorkIndex, ValueCount); - typedef _1 InputDomain; + using InputDomain = _1; template DeviceAdapterTraits; + using DeviceAdapterTraits = vtkm::cont::DeviceAdapterTraits; std::cout << "Testing Map Field on device adapter: " << DeviceAdapterTraits::GetName() << std::endl; diff --git a/vtkm/worklet/tetrahedralize/TetrahedralizeExplicit.h b/vtkm/worklet/tetrahedralize/TetrahedralizeExplicit.h index 26b14245a..39e8155b2 100644 --- a/vtkm/worklet/tetrahedralize/TetrahedralizeExplicit.h +++ b/vtkm/worklet/tetrahedralize/TetrahedralizeExplicit.h @@ -57,7 +57,7 @@ public: public: typedef void ControlSignature(FieldIn<> shapes, ExecObject tables, FieldOut<> tetrahedronCount); typedef _3 ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_CONT TetrahedraPerCell() {} @@ -83,9 +83,9 @@ public: ExecObject tables, FieldOutCell<> connectivityOut); typedef void ExecutionSignature(CellShape, PointIndices, _2, _3, VisitIndex); - typedef _1 InputDomain; + using InputDomain = _1; - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } diff --git a/vtkm/worklet/tetrahedralize/TetrahedralizeStructured.h b/vtkm/worklet/tetrahedralize/TetrahedralizeStructured.h index 75c01053d..a9f2dc653 100644 --- a/vtkm/worklet/tetrahedralize/TetrahedralizeStructured.h +++ b/vtkm/worklet/tetrahedralize/TetrahedralizeStructured.h @@ -56,9 +56,9 @@ public: public: typedef void ControlSignature(CellSetIn cellset, FieldOutCell<> connectivityOut); typedef void ExecutionSignature(PointIndices, _2, ThreadIndices); - typedef _1 InputDomain; + using InputDomain = _1; - typedef vtkm::worklet::ScatterUniform ScatterType; + using ScatterType = vtkm::worklet::ScatterUniform; VTKM_CONT ScatterType GetScatter() const { return ScatterType(5); } @@ -94,7 +94,7 @@ public: vtkm::cont::CellSetSingleType<> Run(const CellSetType& cellSet, vtkm::cont::ArrayHandle& outCellsPerCell) { - typedef vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::CellSetSingleType<> outCellSet(cellSet.GetName()); vtkm::cont::ArrayHandle connectivity; diff --git a/vtkm/worklet/triangulate/TriangulateExplicit.h b/vtkm/worklet/triangulate/TriangulateExplicit.h index c214cbaed..0876efad6 100644 --- a/vtkm/worklet/triangulate/TriangulateExplicit.h +++ b/vtkm/worklet/triangulate/TriangulateExplicit.h @@ -60,7 +60,7 @@ public: ExecObject tables, FieldOut<> triangleCount); typedef _4 ExecutionSignature(_1, _2, _3); - typedef _1 InputDomain; + using InputDomain = _1; VTKM_CONT TrianglesPerCell() {} @@ -86,9 +86,9 @@ public: ExecObject tables, FieldOutCell<> connectivityOut); typedef void ExecutionSignature(CellShape, PointIndices, _2, _3, VisitIndex); - typedef _1 InputDomain; + using InputDomain = _1; - typedef vtkm::worklet::ScatterCounting ScatterType; + using ScatterType = vtkm::worklet::ScatterCounting; VTKM_CONT ScatterType GetScatter() const { return this->Scatter; } diff --git a/vtkm/worklet/triangulate/TriangulateStructured.h b/vtkm/worklet/triangulate/TriangulateStructured.h index 43307996d..6e9443842 100644 --- a/vtkm/worklet/triangulate/TriangulateStructured.h +++ b/vtkm/worklet/triangulate/TriangulateStructured.h @@ -56,9 +56,9 @@ public: public: typedef void ControlSignature(CellSetIn cellset, FieldOutCell<> connectivityOut); typedef void ExecutionSignature(PointIndices, _2, VisitIndex); - typedef _1 InputDomain; + using InputDomain = _1; - typedef vtkm::worklet::ScatterUniform ScatterType; + using ScatterType = vtkm::worklet::ScatterUniform; VTKM_CONT ScatterType GetScatter() const { return ScatterType(2); } @@ -84,7 +84,7 @@ public: vtkm::cont::ArrayHandle& outCellsPerCell) { - typedef vtkm::cont::DeviceAdapterAlgorithm DeviceAlgorithm; + using DeviceAlgorithm = vtkm::cont::DeviceAdapterAlgorithm; vtkm::cont::CellSetSingleType<> outCellSet(cellSet.GetName()); vtkm::cont::ArrayHandle connectivity; diff --git a/vtkm/worklet/wavelets/WaveletBase.h b/vtkm/worklet/wavelets/WaveletBase.h index c0ec5ed97..fec15c4d8 100644 --- a/vtkm/worklet/wavelets/WaveletBase.h +++ b/vtkm/worklet/wavelets/WaveletBase.h @@ -110,7 +110,7 @@ public: vtkm::Id startIdx, DeviceTag) { - typedef vtkm::worklet::wavelets::CopyWorklet CopyType; + using CopyType = vtkm::worklet::wavelets::CopyWorklet; CopyType cp(startIdx); vtkm::worklet::DispatcherMapField dispatcher(cp); dispatcher.Invoke(srcArray, dstArray); @@ -120,7 +120,7 @@ public: template void DeviceAssignZero(ArrayType& array, vtkm::Id index, DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZeroWorklet ZeroWorklet; + using ZeroWorklet = vtkm::worklet::wavelets::AssignZeroWorklet; ZeroWorklet worklet(index); vtkm::worklet::DispatcherMapField dispatcher(worklet); dispatcher.Invoke(array); @@ -134,7 +134,7 @@ public: vtkm::Id rowIdx, DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZero2DWorklet AssignZero2DType; + using AssignZero2DType = vtkm::worklet::wavelets::AssignZero2DWorklet; AssignZero2DType zeroWorklet(dimX, dimY, -1, rowIdx); vtkm::worklet::DispatcherMapField dispatcher(zeroWorklet); dispatcher.Invoke(array); @@ -148,7 +148,7 @@ public: vtkm::Id colIdx, DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZero2DWorklet AssignZero2DType; + using AssignZero2DType = vtkm::worklet::wavelets::AssignZero2DWorklet; AssignZero2DType zeroWorklet(dimX, dimY, colIdx, -1); vtkm::worklet::DispatcherMapField dispatcher(zeroWorklet); dispatcher.Invoke(array); @@ -163,7 +163,7 @@ public: vtkm::Id zeroX, // X idx to set zero DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZero3DWorklet AssignZero3DType; + using AssignZero3DType = vtkm::worklet::wavelets::AssignZero3DWorklet; AssignZero3DType zeroWorklet(dimX, dimY, dimZ, zeroX, -1, -1); vtkm::worklet::DispatcherMapField dispatcher(zeroWorklet); dispatcher.Invoke(array); @@ -178,7 +178,7 @@ public: vtkm::Id zeroY, // Y idx to set zero DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZero3DWorklet AssignZero3DType; + using AssignZero3DType = vtkm::worklet::wavelets::AssignZero3DWorklet; AssignZero3DType zeroWorklet(dimX, dimY, dimZ, -1, zeroY, -1); vtkm::worklet::DispatcherMapField dispatcher(zeroWorklet); dispatcher.Invoke(array); @@ -193,7 +193,7 @@ public: vtkm::Id zeroZ, // Y idx to set zero DeviceTag) { - typedef vtkm::worklet::wavelets::AssignZero3DWorklet AssignZero3DType; + using AssignZero3DType = vtkm::worklet::wavelets::AssignZero3DWorklet; AssignZero3DType zeroWorklet(dimX, dimY, dimZ, -1, -1, zeroZ); vtkm::worklet::DispatcherMapField dispatcher(zeroWorklet); dispatcher.Invoke(array); @@ -280,7 +280,7 @@ public: vtkm::cont::ArrayHandle squaredDeviation; // Use a worklet - typedef vtkm::worklet::wavelets::SquaredDeviation SDWorklet; + using SDWorklet = vtkm::worklet::wavelets::SquaredDeviation; SDWorklet sdw(mean); vtkm::worklet::DispatcherMapField dispatcher(sdw); dispatcher.Invoke(array, squaredDeviation); @@ -303,7 +303,7 @@ public: vtkm::Id startY, DeviceTag) { - typedef vtkm::worklet::wavelets::RectangleCopyTo CopyToWorklet; + using CopyToWorklet = vtkm::worklet::wavelets::RectangleCopyTo; CopyToWorklet cp(smallX, smallY, bigX, bigY, startX, startY); vtkm::worklet::DispatcherMapField dispatcher(cp); dispatcher.Invoke(smallRect, bigRect); @@ -324,7 +324,7 @@ public: vtkm::Id startZ, DeviceTag) { - typedef vtkm::worklet::wavelets::CubeCopyTo CopyToWorklet; + using CopyToWorklet = vtkm::worklet::wavelets::CubeCopyTo; CopyToWorklet cp(smallX, smallY, smallZ, bigX, bigY, bigZ, startX, startY, startZ); vtkm::worklet::DispatcherMapField dispatcher(cp); dispatcher.Invoke(smallCube, bigCube); diff --git a/vtkm/worklet/wavelets/WaveletDWT.h b/vtkm/worklet/wavelets/WaveletDWT.h index 1cd69d582..fc10c4f1a 100644 --- a/vtkm/worklet/wavelets/WaveletDWT.h +++ b/vtkm/worklet/wavelets/WaveletDWT.h @@ -88,10 +88,10 @@ public: return 0; } - typedef typename SigInArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ExtendArrayType; - typedef vtkm::worklet::wavelets::ExtensionWorklet3D ExtensionWorklet; - typedef typename vtkm::worklet::DispatcherMapField DispatcherType; + using ValueType = typename SigInArrayType::ValueType; + using ExtendArrayType = vtkm::cont::ArrayHandle; + using ExtensionWorklet = vtkm::worklet::wavelets::ExtensionWorklet3D; + using DispatcherType = typename vtkm::worklet::DispatcherMapField; vtkm::Id extDimX, extDimY, extDimZ; vtkm::worklet::wavelets::ExtensionDirection dir; @@ -150,7 +150,7 @@ public: else if (!pretendSigPaddedZero && padZeroAtExt2) { // This case is not exactly padding a zero at the end of Ext2. // Rather, it is to increase extension length by one and fill it - // to be whatever mirrorred. + // to be whatever mirrored. extDimX = addLen + 1; ext2.PrepareForOutput(extDimX * extDimY * extDimZ, DeviceTag()); ExtensionWorklet worklet(extDimX, @@ -253,10 +253,10 @@ public: return 0; } - typedef typename SigInArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ExtendArrayType; - typedef vtkm::worklet::wavelets::ExtensionWorklet3D ExtensionWorklet; - typedef typename vtkm::worklet::DispatcherMapField DispatcherType; + using ValueType = typename SigInArrayType::ValueType; + using ExtendArrayType = vtkm::cont::ArrayHandle; + using ExtensionWorklet = vtkm::worklet::wavelets::ExtensionWorklet3D; + using DispatcherType = typename vtkm::worklet::DispatcherMapField; vtkm::Id extDimX, extDimY, extDimZ; vtkm::worklet::wavelets::ExtensionDirection dir; @@ -315,7 +315,7 @@ public: else if (!pretendSigPaddedZero && padZeroAtExt2) { // This case is not exactly padding a zero at the end of Ext2. // Rather, it is to increase extension length by one and fill it - // to be whatever mirrorred. + // to be whatever mirrored. extDimY = addLen + 1; ext2.PrepareForOutput(extDimX * extDimY * extDimZ, DeviceTag()); ExtensionWorklet worklet(extDimX, @@ -418,10 +418,10 @@ public: return 0; } - typedef typename SigInArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ExtendArrayType; - typedef vtkm::worklet::wavelets::ExtensionWorklet3D ExtensionWorklet; - typedef typename vtkm::worklet::DispatcherMapField DispatcherType; + using ValueType = typename SigInArrayType::ValueType; + using ExtendArrayType = vtkm::cont::ArrayHandle; + using ExtensionWorklet = vtkm::worklet::wavelets::ExtensionWorklet3D; + using DispatcherType = typename vtkm::worklet::DispatcherMapField; vtkm::Id extDimX, extDimY, extDimZ; vtkm::worklet::wavelets::ExtensionDirection dir; @@ -480,7 +480,7 @@ public: else if (!pretendSigPaddedZero && padZeroAtExt2) { // This case is not exactly padding a zero at the end of Ext2. // Rather, it is to increase extension length by one and fill it - // to be whatever mirrorred. + // to be whatever mirrored. extDimZ = addLen + 1; ext2.PrepareForOutput(extDimX * extDimY * extDimZ, DeviceTag()); ExtensionWorklet worklet(extDimX, @@ -630,16 +630,16 @@ public: } vtkm::Id addLen = filterLen / 2; - typedef typename ArrayInType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ArrayType; - typedef vtkm::worklet::wavelets::ForwardTransform3DLeftRight LeftRightXFormType; - typedef vtkm::worklet::wavelets::ForwardTransform3DTopDown TopDownXFormType; - typedef vtkm::worklet::wavelets::ForwardTransform3DFrontBack FrontBackXFormType; - typedef vtkm::worklet::DispatcherMapField - LeftRightDispatcherType; - typedef vtkm::worklet::DispatcherMapField TopDownDispatcherType; - typedef vtkm::worklet::DispatcherMapField - FrontBackDispatcherType; + using ValueType = typename ArrayInType::ValueType; + using ArrayType = vtkm::cont::ArrayHandle; + using LeftRightXFormType = vtkm::worklet::wavelets::ForwardTransform3DLeftRight; + using TopDownXFormType = vtkm::worklet::wavelets::ForwardTransform3DTopDown; + using FrontBackXFormType = vtkm::worklet::wavelets::ForwardTransform3DFrontBack; + using LeftRightDispatcherType = + vtkm::worklet::DispatcherMapField; + using TopDownDispatcherType = vtkm::worklet::DispatcherMapField; + using FrontBackDispatcherType = + vtkm::worklet::DispatcherMapField; vtkm::cont::Timer timer; vtkm::Float64 computationTime = 0.0; @@ -821,15 +821,15 @@ public: vtkm::Id inPretendDimZ = L[2] + L[5]; vtkm::Id filterLen = WaveletBase::filter.GetFilterLength(); - typedef vtkm::cont::ArrayHandle BasicArrayType; - typedef vtkm::worklet::wavelets::InverseTransform3DLeftRight LeftRightXFormType; - typedef vtkm::worklet::wavelets::InverseTransform3DTopDown TopDownXFormType; - typedef vtkm::worklet::wavelets::InverseTransform3DFrontBack FrontBackXFormType; - typedef vtkm::worklet::DispatcherMapField - LeftRightDispatcherType; - typedef vtkm::worklet::DispatcherMapField TopDownDispatcherType; - typedef vtkm::worklet::DispatcherMapField - FrontBackDispatcherType; + using BasicArrayType = vtkm::cont::ArrayHandle; + using LeftRightXFormType = vtkm::worklet::wavelets::InverseTransform3DLeftRight; + using TopDownXFormType = vtkm::worklet::wavelets::InverseTransform3DTopDown; + using FrontBackXFormType = vtkm::worklet::wavelets::InverseTransform3DFrontBack; + using LeftRightDispatcherType = + vtkm::worklet::DispatcherMapField; + using TopDownDispatcherType = vtkm::worklet::DispatcherMapField; + using FrontBackDispatcherType = + vtkm::worklet::DispatcherMapField; vtkm::cont::Timer timer; vtkm::Float64 computationTime = 0.0; @@ -1081,10 +1081,10 @@ public: return 0; } - typedef typename SigInArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ExtendArrayType; - typedef vtkm::worklet::wavelets::ExtensionWorklet2D ExtensionWorklet; - typedef typename vtkm::worklet::DispatcherMapField DispatcherType; + using ValueType = typename SigInArrayType::ValueType; + using ExtendArrayType = vtkm::cont::ArrayHandle; + using ExtensionWorklet = vtkm::worklet::wavelets::ExtensionWorklet2D; + using DispatcherType = typename vtkm::worklet::DispatcherMapField; vtkm::Id extDimX, extDimY; vtkm::worklet::wavelets::ExtensionDirection dir; @@ -1251,9 +1251,9 @@ public: // "right extension" can be attached a zero on either end, but not both ends. VTKM_ASSERT(!attachZeroRightRight || !attachZeroRightLeft); - typedef typename SigInArrayType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ExtensionArrayType; - typedef vtkm::cont::ArrayHandleConcatenate ArrayConcat; + using ValueType = typename SigInArrayType::ValueType; + using ExtensionArrayType = vtkm::cont::ArrayHandle; + using ArrayConcat = vtkm::cont::ArrayHandleConcatenate; ExtensionArrayType leftExtend, rightExtend; @@ -1278,14 +1278,14 @@ public: leftExtend.PrepareForOutput(addLen, DeviceTag()); vtkm::Id sigInLen = sigIn.GetNumberOfValues(); - typedef vtkm::worklet::wavelets::LeftSYMHExtentionWorklet LeftSYMH; - typedef vtkm::worklet::wavelets::LeftSYMWExtentionWorklet LeftSYMW; - typedef vtkm::worklet::wavelets::RightSYMHExtentionWorklet RightSYMH; - typedef vtkm::worklet::wavelets::RightSYMWExtentionWorklet RightSYMW; - typedef vtkm::worklet::wavelets::LeftASYMHExtentionWorklet LeftASYMH; - typedef vtkm::worklet::wavelets::LeftASYMWExtentionWorklet LeftASYMW; - typedef vtkm::worklet::wavelets::RightASYMHExtentionWorklet RightASYMH; - typedef vtkm::worklet::wavelets::RightASYMWExtentionWorklet RightASYMW; + using LeftSYMH = vtkm::worklet::wavelets::LeftSYMHExtentionWorklet; + using LeftSYMW = vtkm::worklet::wavelets::LeftSYMWExtentionWorklet; + using RightSYMH = vtkm::worklet::wavelets::RightSYMHExtentionWorklet; + using RightSYMW = vtkm::worklet::wavelets::RightSYMWExtentionWorklet; + using LeftASYMH = vtkm::worklet::wavelets::LeftASYMHExtentionWorklet; + using LeftASYMW = vtkm::worklet::wavelets::LeftASYMWExtentionWorklet; + using RightASYMH = vtkm::worklet::wavelets::RightASYMHExtentionWorklet; + using RightASYMW = vtkm::worklet::wavelets::RightASYMWExtentionWorklet; switch (leftExtMethod) { @@ -1379,7 +1379,7 @@ public: } else // attachZeroRightLeft mode { - typedef vtkm::cont::ArrayHandleConcatenate ConcatArray; + using ConcatArray = vtkm::cont::ArrayHandleConcatenate; // attach a zero at the end of sigIn ExtensionArrayType singleValArray; singleValArray.PrepareForOutput(1, DeviceTag()); @@ -1497,11 +1497,11 @@ public: vtkm::Id sigExtendedLen = sigInLen + 2 * addLen; - typedef typename SignalArrayType::ValueType SigInValueType; - typedef vtkm::cont::ArrayHandle SigInBasic; + using SigInValueType = typename SignalArrayType::ValueType; + using SigInBasic = vtkm::cont::ArrayHandle; - typedef vtkm::cont::ArrayHandleConcatenate ConcatType1; - typedef vtkm::cont::ArrayHandleConcatenate ConcatType2; + using ConcatType1 = vtkm::cont::ArrayHandleConcatenate; + using ConcatType2 = vtkm::cont::ArrayHandleConcatenate; ConcatType2 sigInExtended; @@ -1610,8 +1610,8 @@ public: cDTempLen = L[1]; } - typedef vtkm::cont::ArrayHandleCounting IdArrayType; - typedef vtkm::cont::ArrayHandlePermutation PermutArrayType; + using IdArrayType = vtkm::cont::ArrayHandleCounting; + using PermutArrayType = vtkm::cont::ArrayHandlePermutation; // Separate cA and cD IdArrayType approxIndices(0, 1, L[0]); @@ -1619,10 +1619,10 @@ public: PermutArrayType cA(approxIndices, coeffIn); PermutArrayType cD(detailIndices, coeffIn); - typedef typename CoeffArrayType::ValueType CoeffValueType; - typedef vtkm::cont::ArrayHandle ExtensionArrayType; - typedef vtkm::cont::ArrayHandleConcatenate Concat1; - typedef vtkm::cont::ArrayHandleConcatenate Concat2; + using CoeffValueType = typename CoeffArrayType::ValueType; + using ExtensionArrayType = vtkm::cont::ArrayHandle; + using Concat1 = vtkm::cont::ArrayHandleConcatenate; + using Concat2 = vtkm::cont::ArrayHandleConcatenate; Concat2 cATemp, cDTemp; @@ -1769,10 +1769,10 @@ public: } vtkm::Id addLen = filterLen / 2; - typedef typename ArrayInType::ValueType ValueType; - typedef vtkm::cont::ArrayHandle ArrayType; - typedef vtkm::worklet::wavelets::ForwardTransform2D ForwardXForm; - typedef typename vtkm::worklet::DispatcherMapField DispatcherType; + using ValueType = typename ArrayInType::ValueType; + using ArrayType = vtkm::cont::ArrayHandle; + using ForwardXForm = vtkm::worklet::wavelets::ForwardTransform2D; + using DispatcherType = typename vtkm::worklet::DispatcherMapField; vtkm::cont::Timer timer; vtkm::Float64 computationTime = 0.0; @@ -1882,9 +1882,9 @@ public: vtkm::Id inPretendDimY = L[1] + L[3]; vtkm::Id filterLen = WaveletBase::filter.GetFilterLength(); - typedef vtkm::cont::ArrayHandle BasicArrayType; - typedef vtkm::worklet::wavelets::InverseTransform2D IDWT2DWorklet; - typedef vtkm::worklet::DispatcherMapField Dispatcher; + using BasicArrayType = vtkm::cont::ArrayHandle; + using IDWT2DWorklet = vtkm::worklet::wavelets::InverseTransform2D; + using Dispatcher = vtkm::worklet::DispatcherMapField; vtkm::cont::Timer timer; vtkm::Float64 computationTime = 0.0; diff --git a/vtkm/worklet/wavelets/WaveletFilter.h b/vtkm/worklet/wavelets/WaveletFilter.h index 21dfdde10..84f6957a3 100644 --- a/vtkm/worklet/wavelets/WaveletFilter.h +++ b/vtkm/worklet/wavelets/WaveletFilter.h @@ -115,7 +115,7 @@ public: bool isSymmetric() { return this->Symmetricity; } - typedef vtkm::cont::ArrayHandle FilterType; + using FilterType = vtkm::cont::ArrayHandle; const FilterType& GetLowDecomposeFilter() const { return this->LowDecomType; } const FilterType& GetHighDecomposeFilter() const { return this->HighDecomType; } diff --git a/vtkm/worklet/wavelets/WaveletTransforms.h b/vtkm/worklet/wavelets/WaveletTransforms.h index bf2da4adb..d8670572d 100644 --- a/vtkm/worklet/wavelets/WaveletTransforms.h +++ b/vtkm/worklet/wavelets/WaveletTransforms.h @@ -59,7 +59,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension WholeArrayIn); // signal typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -851,7 +851,7 @@ public: WholeArrayIn, // right extension WholeArrayOut); // cA followed by cD typedef void ExecutionSignature(_1, _2, _3, _4, WorkIndex); - typedef _4 InputDomain; + using InputDomain = _4; ForwardTransform3DLeftRight(const vtkm::cont::ArrayHandle& loFilter, const vtkm::cont::ArrayHandle& hiFilter, @@ -954,7 +954,7 @@ public: vtkm::Id workX, workY, workZ, output1D; Output1Dto3D(workIndex, workX, workY, workZ); vtkm::Id inputCube, inputIdx; - typedef typename OutputPortalType::ValueType OutputValueType; + using OutputValueType = typename OutputPortalType::ValueType; if (workX % 2 == 0) // calculate cA { @@ -1005,7 +1005,7 @@ public: WholeArrayIn, // right extension WholeArrayOut); // cA followed by cD typedef void ExecutionSignature(_1, _2, _3, _4, WorkIndex); - typedef _4 InputDomain; + using InputDomain = _4; ForwardTransform3DTopDown(const vtkm::cont::ArrayHandle& loFilter, const vtkm::cont::ArrayHandle& hiFilter, @@ -1108,7 +1108,7 @@ public: vtkm::Id workX, workY, workZ, output1D; Output1Dto3D(workIndex, workX, workY, workZ); vtkm::Id inputCube, inputIdx; - typedef typename OutputPortalType::ValueType OutputValueType; + using OutputValueType = typename OutputPortalType::ValueType; if (workY % 2 == 0) // calculate cA { @@ -1159,7 +1159,7 @@ public: WholeArrayIn, // right extension WholeArrayOut); // cA followed by cD typedef void ExecutionSignature(_1, _2, _3, _4, WorkIndex); - typedef _4 InputDomain; + using InputDomain = _4; ForwardTransform3DFrontBack(const vtkm::cont::ArrayHandle& loFilter, const vtkm::cont::ArrayHandle& hiFilter, @@ -1262,7 +1262,7 @@ public: vtkm::Id workX, workY, workZ, output1D; Output1Dto3D(workIndex, workX, workY, workZ); vtkm::Id inputCube, inputIdx; - typedef typename OutputPortalType::ValueType OutputValueType; + using OutputValueType = typename OutputPortalType::ValueType; if (workZ % 2 == 0) // calculate cA { @@ -1328,7 +1328,7 @@ public: WholeArrayIn, // cA+cD (signal) FieldOut); // outptu coefficients typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); - typedef _6 InputDomain; + using InputDomain = _6; // Constructor InverseTransform3DLeftRight(const vtkm::cont::ArrayHandle& lo_fil, @@ -1560,7 +1560,7 @@ public: WholeArrayIn, // cA+cD (signal) FieldOut); // outptu coefficients typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); - typedef _6 InputDomain; + using InputDomain = _6; // Constructor InverseTransform3DTopDown(const vtkm::cont::ArrayHandle& lo_fil, @@ -1792,7 +1792,7 @@ public: WholeArrayIn, // cA+cD (signal) FieldOut); // outptu coefficients typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); - typedef _6 InputDomain; + using InputDomain = _6; // Constructor InverseTransform3DFrontBack(const vtkm::cont::ArrayHandle& lo_fil, @@ -2259,7 +2259,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -2406,7 +2406,7 @@ public: WholeArrayIn, // right/bottom extension WholeArrayOut); // cA followed by cD typedef void ExecutionSignature(_1, _2, _3, _4, WorkIndex); - typedef _4 InputDomain; + using InputDomain = _4; // Constructor ForwardTransform2D(const vtkm::cont::ArrayHandle& loFilter, @@ -2488,7 +2488,7 @@ public: vtkm::Id workX, workY, output1D; Output1Dto2D(workIndex, workX, workY); vtkm::Id inputMatrix, inputIdx; - typedef typename OutputPortalType::ValueType OutputValueType; + using OutputValueType = typename OutputPortalType::ValueType; if (modeLR) { @@ -2595,7 +2595,7 @@ public: WholeArrayIn, // cA+cD (signal) FieldOut); // outptu coeffs typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, WorkIndex); - typedef _6 InputDomain; + using InputDomain = _6; // Constructor InverseTransform2D(const vtkm::cont::ArrayHandle& lo_fil, @@ -2899,7 +2899,7 @@ public: typedef void ControlSignature(WholeArrayIn, // sigIn WholeArrayOut); // cA followed by cD typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor ForwardTransform(const vtkm::cont::ArrayHandle& loFilter, @@ -2928,7 +2928,7 @@ public: OutputPortalType& coeffOut, const vtkm::Id& workIndex) const { - typedef typename OutputPortalType::ValueType OutputValueType; + using OutputValueType = typename OutputPortalType::ValueType; if (workIndex < approxLen + detailLen) { if (workIndex % 2 == 0) // calculate cA @@ -2983,7 +2983,7 @@ public: // cA followed by cD WholeArrayOut); // output typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3065,7 +3065,7 @@ public: // cA followed by cD WholeArrayOut); // output typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor InverseTransformEven(const vtkm::cont::ArrayHandle& loFilter, @@ -3154,7 +3154,7 @@ class ThresholdWorklet : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldInOut); // Thresholding in-place typedef void ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor ThresholdWorklet(vtkm::Float64 t) @@ -3183,7 +3183,7 @@ class SquaredDeviation : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn, FieldOut); typedef _2 ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor template @@ -3209,7 +3209,7 @@ class Differencer : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn, FieldIn, FieldOut); typedef _3 ExecutionSignature(_1, _2); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC ValueType1 operator()(const ValueType1& v1, const ValueType2& v2) const @@ -3223,7 +3223,7 @@ class SquareWorklet : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(FieldIn, FieldOut); typedef _2 ExecutionSignature(_1); - typedef _1 InputDomain; + using InputDomain = _1; template VTKM_EXEC ValueType operator()(const ValueType& v) const @@ -3237,7 +3237,7 @@ class CopyWorklet : public vtkm::worklet::WorkletMapField public: typedef void ControlSignature(WholeArrayIn, WholeArrayOut); typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3262,7 +3262,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3290,7 +3290,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3318,7 +3318,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3346,7 +3346,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3374,7 +3374,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3402,7 +3402,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3430,7 +3430,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3458,7 +3458,7 @@ public: typedef void ControlSignature(WholeArrayOut, // extension part WholeArrayIn); // signal part typedef void ExecutionSignature(_1, _2, WorkIndex); - typedef _1 InputDomain; + using InputDomain = _1; // Constructor VTKM_EXEC_CONT @@ -3614,7 +3614,7 @@ private: // each becomes a wild card if negative }; -// Worklet: Copys a small rectangle to become a part of a big rectangle +// Worklet: Copies a small rectangle to become a part of a big rectangle class RectangleCopyTo : public vtkm::worklet::WorkletMapField { public: @@ -3668,7 +3668,7 @@ private: vtkm::Id outXStart, outYStart; }; -// Worklet: Copys a small cube to become a part of a big cube +// Worklet: Copies a small cube to become a part of a big cube class CubeCopyTo : public vtkm::worklet::WorkletMapField { public: